<?php
class ome_ctl_admin_order extends desktop_controller{
    var $name = "订单中心";
    var $workground = "order_center";
    var $order_type = 'all';

    function _views(){
        if($this->order_type == 'abnormal'){
           $sub_menu = $this->_viewsAbnormal();
        }elseif($this->order_type == 'assigned'){
           $sub_menu = $this->_views_assigned();
        }elseif($this->order_type == 'notassigned'){
           $sub_menu = $this->_views_notassigned();
        }elseif($this->order_type == 'unmyown'){
           $sub_menu = $this->_views_unmyown();
        }elseif($this->order_type == 'myown'){
           $sub_menu = $this->_views_myown();
        }elseif($this->order_type == 'ourgroup'){
           $sub_menu = $this->_views_ourgroup();
        }else{
           $sub_menu = $this->_viewsAll();
        }
        return $sub_menu;
    }

    function _viewsAll(){
        $mdl_order = $this->app->model('orders');
        $base_filter = array('disabled'=>'false','is_fail'=>'false');
        $sub_menu = array(
            0 => array('label'=>app::get('base')->_('全部'),'filter'=>$base_filter,'optional'=>false),
            1 => array('label'=>app::get('base')->_('货到付款'),'filter'=>array('is_cod'=>'true','status' => 'active'),'optional'=>false),
            2 => array('label'=>app::get('base')->_('待支付'),'filter'=>array('pay_status' => array('0','3'),'status' => 'active'),'optional'=>false),
            3 => array('label'=>app::get('base')->_('已支付'),'filter'=>array('pay_status' => 1,'status' => 'active'),'optional'=>false),
            4 => array(
                'label'=>app::get('base')->_('待处理'),
                'filter'=>array(
                    'abnormal'=>'false',
                    'order_confirm_filter'=>'group_id > 0',
                    'process_status'=>array('unconfirmed','confirmed','splitting'),
                    'status'=>'active'),
                'optional'=>false),
            5 => array(
                'label'=>app::get('base')->_('已处理'),
                'filter'=>array('abnormal'=>'false','order_confirm_filter'=>'group_id > 0','process_status'=>array('splited','remain_cancel'),'status' => 'active'),
                'optional'=>false),
            6 => array('label'=>app::get('base')->_('待发货'),'filter'=>array('ship_status' =>array('0','2'),'status' => 'active'),'optional'=>false),
            7 => array('label'=>app::get('base')->_('已发货'),'filter'=>array('ship_status' =>'1','status' => 'active'),'optional'=>false),
            8 => array('label'=>app::get('base')->_('取消'),'filter'=>array('process_status' => 'cancel'),'optional'=>false),
            9 => array('label'=>app::get('base')->_('暂停'),'filter'=>array('pause' => 'true'),'optional'=>false),
        );
        $i=0;
        foreach($sub_menu as $k=>$v){
            if (!IS_NULL($v['filter'])){
                $v['filter'] = array_merge($v['filter'], $base_filter);
            }
            $sub_menu[$k]['filter'] = $v['filter']?$v['filter']:null;
            $sub_menu[$k]['addon'] = $mdl_order->count($v['filter']);
            $sub_menu[$k]['href'] = 'index.php?app=ome&ctl='.$_GET['ctl'].'&act='.$_GET['act'].'&view='.$i++;
        }
        return $sub_menu;
    }

    /*
     * 已分派订单标签
     */
    function _views_assigned(){
        $mdl_order = $this->app->model('orders');
        $base_filter = array(
            'assigned'=>'assigned',
            'abnormal'=>'false',
            'is_fail'=>'false',
            'process_status|noequal'=>'cancel',
            'is_auto'=>'false');
        $sub_menu = array(
            0 => array('label'=>app::get('base')->_('全部'),'filter'=>$base_filter,'optional'=>false),
        );
        $groupsObj = &$this->app->model("groups");
        $groups = $groupsObj->getList('*');
        foreach($groups as $group){
            $sub_menu[] = array(
                'label'=>$group['name'],
                'filter'=>array('group_id'=>$group['group_id']),
                'optional'=>false
            );
        }
        $i=0;
        foreach($sub_menu as $k=>$v){
            if (!IS_NULL($v['filter'])){
                $v['filter'] = array_merge($v['filter'], $base_filter);
            }
            $sub_menu[$k]['filter'] = $v['filter']?$v['filter']:null;
            $sub_menu[$k]['addon'] = $mdl_order->count($v['filter']);
            $sub_menu[$k]['href'] = 'index.php?app=ome&ctl='.$_GET['ctl'].'&act='.$_GET['act'].'&flt=assigned&view='.$i++;
        }
        return $sub_menu;
    }

    /*
     * 未分派订单标签
     */
    function _views_notassigned(){
        $mdl_order = $this->app->model('orders');
        $base_filter = array(
            'assigned'=>'notassigned',
            'abnormal'=>'false',
            'is_fail'=>'false',
            'ship_status'=>'0',
            'process_status|noequal'=>'cancel',
            'is_auto'=>'false');
        $sub_menu = array(
            0 => array('label'=>app::get('base')->_('全部'),'filter'=>$base_filter,'optional'=>false),
            1 => array('label'=>app::get('base')->_('货到付款'),'filter'=>array('is_cod'=>'true'),'optional'=>false),
            2 => array('label'=>app::get('base')->_('待支付'),'filter'=>array('pay_status' => array('0','3')),'optional'=>false),
            3 => array('label'=>app::get('base')->_('已支付'),'filter'=>array('pay_status' => 1),'optional'=>false),
        );
        $i=0;
        foreach($sub_menu as $k=>$v){
            if (!IS_NULL($v['filter'])){
                $v['filter'] = array_merge($v['filter'], $base_filter);
            }
            $sub_menu[$k]['filter'] = $v['filter']?$v['filter']:null;
            $sub_menu[$k]['addon'] = $mdl_order->count($v['filter']);
            $sub_menu[$k]['href'] = 'index.php?app=ome&ctl='.$_GET['ctl'].'&act='.$_GET['act'].'&flt=notassigned&view='.$i++;
        }
        return $sub_menu;
    }

    /*
     * 待处理订单标签
     */
    function _views_unmyown(){
        $mdl_order = $this->app->model('orders');
        $base_filter = array(
            'assigned'=>'assigned',
            'abnormal'=>'false',
            'is_fail'=>'false');

        $base_filter['op_id'] = kernel::single('desktop_user')->get_id();
        // 超级管理员
        if(kernel::single('desktop_user')->is_super()){
            if(isset($base_filter['op_id'])){
                unset($base_filter['op_id']);
            }
        }

        $sub_menu = array(
            0 => array('label'=>app::get('base')->_('全部'),'filter'=>array('process_status'=>array('unconfirmed','confirmed','splitting')),'optional'=>false),
            1 => array('label'=>app::get('base')->_('未确认'),'filter'=>array('confirm'=>'N','process_status' =>'unconfirmed'),'optional'=>false),
            2 => array('label'=>app::get('base')->_('已确认'),'filter'=>array('confirm'=>'Y','process_status' =>'confirmed'),'optional'=>false),
            3 => array('label'=>app::get('base')->_('部分拆分'),'filter'=>array('process_status' =>'splitting'),'optional'=>false),
            4 => array(
                'label'=>app::get('base')->_('部分发货'),
                'filter'=>array('ship_status' =>'2','process_status'=>array('unconfirmed','confirmed','splitting')),
                'optional'=>false),
            5 => array(
                'label'=>app::get('base')->_('暂停'),
                'filter'=>array('pause' => 'true','process_status'=>array('unconfirmed','confirmed','splitting')),
                'optional'=>false),
            6 => array(
                'label'=>app::get('base')->_('部分付款'),
                'filter'=>array('pay_status' =>'3','process_status'=>array('unconfirmed','confirmed','splitting')),
                'optional'=>false),
            7 => array(
                'label'=>app::get('base')->_('部分退款'),
                'filter'=>array('pay_status' =>'4','process_status'=>array('unconfirmed','confirmed','splitting')),
                'optional'=>false),
        );
        $i=0;
        foreach($sub_menu as $k=>$v){
            if (!IS_NULL($v['filter'])){
                $v['filter'] = array_merge($v['filter'], $base_filter);
            }
            $sub_menu[$k]['filter'] = $v['filter']?$v['filter']:null;
            $sub_menu[$k]['addon'] = $mdl_order->count($v['filter']);
            $sub_menu[$k]['href'] = 'index.php?app=ome&ctl='.$_GET['ctl'].'&act='.$_GET['act'].'&flt=unmyown&view='.$i++;
        }
        return $sub_menu;
    }

    /*
     * 已处理订单标签
     */
    function _views_myown(){
        $mdl_order = $this->app->model('orders');
        $base_filter = array(
            'assigned'=>'assigned',
            'abnormal'=>'false',
            'is_fail'=>'false',);

        $base_filter['op_id'] = kernel::single('desktop_user')->get_id();
        // 超级管理员
        if(kernel::single('desktop_user')->is_super()){
            if(isset($base_filter['op_id'])){
                unset($base_filter['op_id']);
            }
        }
//        $base_filter['order_confirm_filter'] = "(is_cod='true' OR pay_status in ('1','4','5'))";

        $sub_menu = array(
            0 => array('label'=>app::get('base')->_('全部'),'filter'=>array('process_status'=>array('splited','remain_cancel','cancel')),'optional'=>false),
            1 => array('label'=>app::get('base')->_('余单撤销'),'filter'=>array('process_status' =>'remain_cancel'),'optional'=>false),
            2 => array(
                'label'=>app::get('base')->_('部分发货'),
                'filter'=>array('ship_status' =>'2','process_status'=>'splited'),
                'optional'=>false),
            3 => array('label'=>app::get('base')->_('已发货'),'filter'=>array('ship_status' =>'1','process_status'=>'splited'),'optional'=>false),
            4 => array('label'=>app::get('base')->_('部分退货'),'filter'=>array('ship_status' =>'3','process_status'=>'splited'),'optional'=>false),
            5 => array(
                'label'=>app::get('base')->_('已退货'),
                'filter'=>array('ship_status' =>'4','process_status'=>'splited'),
                'optional'=>false),
            6 => array(
                'label'=>app::get('base')->_('暂停'),
                'filter'=>array('pause' => 'true','process_status'=>'splited'),
                'optional'=>false),
        );
        $i=0;
        foreach($sub_menu as $k=>$v){
            if (!IS_NULL($v['filter'])){
                $v['filter'] = array_merge($v['filter'], $base_filter);
            }
            $sub_menu[$k]['filter'] = $v['filter']?$v['filter']:null;
            $sub_menu[$k]['addon'] = $mdl_order->count($v['filter']);
            $sub_menu[$k]['href'] = 'index.php?app=ome&ctl='.$_GET['ctl'].'&act='.$_GET['act'].'&flt=myown&view='.$i++;
        }
        return $sub_menu;
    }

    /*
     * 本组订单标签
     */
    function _views_ourgroup(){
        $mdl_order = $this->app->model('orders');
        $base_filter = array(
            'assigned'=>'assigned',
            'abnormal'=>'false',
            'is_fail'=>'false',
            'process_status'=>array('unconfirmed','confirmed','splitting','splited','remain_cancel')
        );

        $groupObj = &$this->app->model("groups");
        $group_id = "";
        $op_id = kernel::single('desktop_user')->get_id();
        $op_group = $groupObj->get_group($op_id);
        if($op_group && is_array($op_group)){
            foreach($op_group as $v){
                $group_id[] = $v['group_id'];
            }
        }
        $base_filter['group_id'] = $group_id;
        // 超级管理员
        if(kernel::single('desktop_user')->is_super()){
            if(isset($base_filter['group_id'])){
                unset($base_filter['group_id']);
            }
        }

        $sub_menu = array(
            0 => array(
                'label'=>app::get('base')->_('全部'),
                'filter'=>array(),
                'optional'=>false
            ),
            1 => array(
                'label'=>app::get('base')->_('待认领'),
                'filter'=>array('order_confirm_filter' =>"op_id is null"),
                'optional'=>false
            ),
        );
        $i=0;
        foreach($sub_menu as $k=>$v){
            if (!IS_NULL($v['filter'])){
                $v['filter'] = array_merge($v['filter'], $base_filter);
            }
            $sub_menu[$k]['filter'] = $v['filter']?$v['filter']:null;
            $sub_menu[$k]['addon'] = $mdl_order->count($v['filter']);
            $sub_menu[$k]['href'] = 'index.php?app=ome&ctl='.$_GET['ctl'].'&act='.$_GET['act'].'&flt=ourgroup&view='.$i++;
        }
        return $sub_menu;
    }

    function _viewsAbnormal(){
        $mdl_order = $this->app->model('orders');
        $abnormal_type_list = app::get('ome')->model('abnormal_type')->getList('*',array('disabled'=>'false'));

        $sub_menu = array();
        $sub_menu[] = array('label'=>app::get('base')->_('全部'),'filter'=>array('abnormal'=>'true','is_fail'=>'false'),'optional'=>false);
        foreach($abnormal_type_list as $abnormal_type){
            $sub_menu[] = array('label'=>$abnormal_type['type_name'],'filter'=>array('abnormal_type_id'=>$abnormal_type['type_id'],'abnormal'=>'true','is_fail'=>'false'),'optional'=>false);

        }

        foreach($sub_menu as $k=>$v){
            $sub_menu[$k]['filter'] = $v['filter']?$v['filter']:null;
            $sub_menu[$k]['addon'] = $mdl_order->countAbnormal($v['filter']);
            $sub_menu[$k]['href'] = 'index.php?app=ome&ctl=admin_order&act=abnormal&view='.$k;
        }
        return $sub_menu;
    }

    function index(){
        $this->title = '订单查看';

        $base_filter = array('disabled'=>'false','is_fail'=>'false');
        $params = array(
            'title'=>$this->title,
            'actions' => array(
                array(
                    'label'=>'导出模板',
                    'href'=>'index.php?app=ome&ctl=admin_order&act=exportTemplate',
                    'target'=>'_blank'
                ),
            		array(
            				'label'=>'导入国美订单',
            				'href'=>'index.php?app=ome&ctl=admin_order&act=importGome',
            				'target'=>"dialog::{width:425,height:150,title:'导入国美订单'}",
            		),
            		array(
            				'label'=>'导出国美订单',
            				'href'=>'index.php?app=ome&ctl=admin_order&act=exportGome',
            				//'target'=>"dialog::{width:425,height:150,title:'导入国美订单'}",
            				'target'=>'_blank'
            		)
            ),
            'use_buildin_new_dialog' => false,
            'use_buildin_set_tag'=>false,
            'use_buildin_recycle'=>false,
            'use_buildin_export'=>true,
            'use_buildin_import'=>true,
            'use_buildin_filter'=>true,
            'use_view_tab'=>true,
            'finder_aliasname'=>'order_view',
            'finder_cols'=>'createtime,shop_id,ship_area,is_cod,total_amount,payment,shipping,mark_type',
            'base_filter' => $base_filter,
       );
       $this->finder('ome_mdl_orders',$params);
    }
	
	/**
	 * 导入国美订单
	 */
	function importGome() {
		if (! $_FILES ['import_file'] ['name']) {
			$this->pagedata ['_finder'] = $_GET ['_finder'] ['finder_id'];
			$this->pagedata ['finder_id'] = $_GET ['finder_id'];
			$this->display ( 'admin/excel/import.html' );
		} else {
			
			// 获取上传的文件名
			$filename = $_FILES ['import_file'] ['name'];
			
			// 上传到服务器上的临时文件名
			$tmp_name = $_FILES ['import_file'] ['tmp_name'];
			$echoMsg = $this->uploadFile ( $filename, $tmp_name );
			
			header ( "content-type:text/html; charset=utf-8" );
			echo "<script>top.MessageBox.success(\"上传成功\");alert(\"" . $echoMsg . "\");if(parent.$('import_form').getParent('.dialog'))parent.$('import_form').getParent('.dialog').retrieve('instance').close();if(parent.window.finderGroup&&parent.window.finderGroup['" . $_GET ['finder_id'] . "'])parent.window.finderGroup['" . $_GET ['finder_id'] . "'].refresh();</script>";
		}
	
	}
	
	/**
	 * 导出国美订单
	 */
	function exportGome() {
			
			/*
		 * $sqlGomeOrder = 'select o.order_bn,ol.operate_time,ol.operation from
		 * sdb_ome_orders o right join sdb_ome_operation_log ol on
		 * o.order_id=ol.`obj_id` where o.shop_type=\'taobao\' and obj_type=\'\'
		 * order by o.order_bn desc,ol.operate_time asc LIMIT 0 , 50';
		 */
		
		$gomeStatus = array (
				'PP',
				'IP',
				'EX' 
		);
		$gomeStatusCN = array (
				iconv ( "UTF-8", "GBK", '已受理' ),
				iconv ( "UTF-8", "GBK", '已派工' ),
				iconv ( "UTF-8", "GBK", '已出库' ) 
		);
		$temArr = array (
				array (
						iconv ( "UTF-8", "GBK", '国美配送订单号' ),
						iconv ( "UTF-8", "GBK", '订单状态变更时间' ),
						iconv ( "UTF-8", "GBK", '订单状态Code' ),
						iconv ( "UTF-8", "GBK", '订单状态名称' ) 
				) 
		);
		
		$db = kernel::database ();
		
		$sqlGomeOrder ="select order_id,confirm,order_bn,ship_status, process_status from sdb_ome_orders where confirm='Y' and shop_type='gome' order by order_bn desc LIMIT 0 , 50";
		$orderlist = $db->select ( $sqlGomeOrder );
		if ($orderlist) {
			 
			foreach ( $orderlist as $key => $item ) {
				$obj_id = $item['order_id'];
				
				// 如果已经确认 查询确认时间
				if($item ['ship_status'] == 1) {// 如果已经发货 查询发货时间
					// sdb_ome_delivery_order
					$sqldellog = "select operate_time from sdb_ome_operation_log ol
					join   sdb_ome_delivery_order  do on ol.obj_id=do.delivery_id
					where  ol.obj_type='delivery@ome' and ol.operation='delivery_process@ome' and  do.order_id='$obj_id'";
					$del = $db->selectrow ( $sqldellog );
						
					$temArr[]  = array (
					$item ['order_bn'],
					date('Y-m-d H:i:s',$del ['operate_time']),
					$gomeStatus [2] ,
					$gomeStatusCN [2]
					);
					 
				}elseif ($item ['process_status'] == 'splited') {// 如果已经拆分完成 查询拆分时间
					$sqlsplog = "select operate_time from sdb_ome_operation_log ol 
											join   sdb_ome_delivery_order  do on ol.obj_id=do.delivery_id
											 where  ol.obj_type='delivery@ome' and ol.operation='delivery_deliv@ome'  and do.order_id='$obj_id'";
					$spl = $db->selectrow ( $sqlsplog );
					//echo $sqlsplog;
						
					$temArr[] = array (
							$item ['order_bn'],
							date('Y-m-d H:i:s',$spl ['operate_time']),
							$gomeStatus [1] ,
							$gomeStatusCN [1]
					);
					
				 
				}elseif  ($item ['confirm'] == 'Y') {
					$sqlcfmlog = "select operate_time from sdb_ome_operation_log where operation='order_confirm@ome' and  obj_id='$obj_id'";
					$cfm = $db->selectrow ( $sqlcfmlog );
				
					$temArr[]  = array (
							$item ['order_bn'],
							date('Y-m-d H:i:s',$cfm ['operate_time']),
							$gomeStatus [0] ,
							$gomeStatusCN [0]
					);
					 
				}
				
			
			}
		 
			//echo "<pre>";
			//var_dump ( $temArr );
			//echo date('Y-m-d H:i:s',1354690037);
			require_once ROOT_DIR . "/app/ome/lib/excel/excel_class.php";
			$echoMsg = "导出成功";
			Create_Excel_File("gomeorder.xls",$temArr);
			//$return=array(array(1,6,1,1,6,1,1),array(1,6,1,1,6,1,1),array(1,4,1,1,5,1,1),array(1,8,1,1,7,1,1),);
			//Create_Excel_File("wew.xls",$return);
		} else {
			$echoMsg = '导出失败,没有满足条件的订单';
		}
		header ( "content-type:text/html; charset=gbk" );
		echo "<script>alert(\"" . $echoMsg . "\");if(parent.$('import_form').getParent('.dialog'))parent.$('import_form').getParent('.dialog').retrieve('instance').close();if(parent.window.finderGroup&&parent.window.finderGroup['" . $_GET ['finder_id'] . "'])parent.window.finderGroup['" . $_GET ['finder_id'] . "'].refresh();</script>";
	
	}

    //导入Excel文件
    function uploadFile($file, $filetempname) {
		if ($file) {
			$tmp_file = $_FILES ['import_file'] ['tmp_name'];
			$file_types = explode ( ".", $_FILES ['import_file'] ['name'] );
			$file_type = $file_types [count ( $file_types ) - 1];
			
			/* 判别是不是.xls文件，判别是不是excel文件 */
			if (strtolower ( $file_type ) != "xls") {
				$msg = '不是Excel文件，重新上传' ;
				return $msg;
			}
			
			/* 设置上传路径 */
			$savePath =ROOT_DIR."/app/ome/upload/upfile/";
			//echo $savePath;
			/* 以时间来命名上传的文件 */
			$str = date ( 'Ymdhis' );
			$file_name = $str . "." . $file_type;
			$uploadfile = $savePath . $file_name;
			/* 是否上传成功 */
			if (! copy ( $tmp_file, $savePath . $file_name )) {
				$msg = '上传失败';
				return $msg;
			}
		
		}
		require_once ROOT_DIR."/app/ome/lib/excel/excel_class.php";
		
		$rt = Read_Excel_File ( $uploadfile, $return );
		
		if ($rt == 0) 		// 如果上传文件成功，就执行导入excel操作
		{
			$return=current($return);
			foreach ( $return as $k => $v ) {
		//	echo "<pre>";
		if($k==0)continue;
			$gomeOrder='{"trade_fullinfo_get_response": { "trade": {
							            "adjust_fee": "0.00",
							            "available_confirm_fee": "604",
							            "buyer_alipay_no": "",
							            "buyer_email": "",
							            "buyer_message": "",
							            "buyer_nick":  "'.$v[17].'",
							            "buyer_name":  "'.$v[17].'",
							            "buyer_tel":  "'.$v[22].'",
							            "buyer_mobile":  "'.$v[23].'",
							            "buyer_zip": "",
							            "buyer_state": "",
							            "buyer_city": "",
							            "buyer_district": "",
							            "buyer_address": "",
							            "buyer_obtain_point_fee": 1560,
							            "buyer_rate": false,
							            "payment_bn": "",
							            "pay_name":  "'.$v[6].'",
							            "pay_time": "'.$v[12].'",
							            "cod_fee": "0.00",
							            "created": "'.$v[4].'",
							            "goods_discount_fee":  "'.$v[16].'",
							            "orders_discount_fee":  "'.$v[16].'",
							            "has_post_fee": true,
							            "modified": "'.$v[4].'",	
							            "orders": {
							                "order": [{
							                        "adjust_fee": "0.00",
							                        "buyer_rate": "false",
							                        "discount_fee": "0.00",
							                        "num": '.$v[24].',
							                        "price": "'.$v[27].'",
							                        "refund_status": "NO_REFUND",
							                        "seller_rate": "false",
							                        "sku_id": "'.$v[25].'",
							                        "outer_sku_id":"'.$v[25].'",
							                        "outer_iid": "'.$v[25].'",                      
							                        "title": "'.$v[26].'",
							                        "total_fee":'.$v[24]*$v[27].'
							                    }
							                ]
							            },
							            "payment":"'.($v[11]+$v[14]+$v[15]).'",
							            "point_fee": 0,
							            "post_fee":"'.$v[28].'",
							            "real_point_fee": 0,
							            "received_payment": "0.00",
							            "receiver_address":"'.$v[18].'",
							            "receiver_city": "'.$v[20].'",
							            "receiver_district": "'.rtrim($v[21],';').'",
							            "receiver_mobile": "'.$v[23].'",
							            "receiver_name": "'.$v[17].'",
							            "receiver_phone": "'.$v[22].'",
							            "receiver_state": "'.$v[19].'",
							            "receiver_zip": "",
							            "seller_memo": "'.$v[10].'",
							            "seller_flag": "0",
							            "shipping_type": "express",
							            "pay_status": "'.$v[7].'",
							            "status":"'.$v[3].'",
							            "invoice_name": "发票类型：'.$v[8].',抬头：'.$v[9].'",
							            "invoice_no": "",
							            "tid": "'.$v[1].'",
							            "title": "国美商城",
							            "total_fee":  "'.($v[11]+$v[14]+$v[15]+$v[16]).'",
							            "total_amount": "'.($v[11]+$v[14]+$v[15]).'",
							            "type":  "'.$v[6].'"
							        }
							    }
							}';
			 
		/*	$order_sdf=json_decode($json,true);
			if (! empty ( $orderOme )) {
			
				if ($this->insertIntoOrder ( $order_sdf, "999999" )) {
					$msg .= "{$tid} done.\n";
				} else {
					$msg .= "{$tid} fail.\n";
					}
					}
		 */
			//post json
		//	echo $gomeOrder;
		
			
		
			$query_params=array('sdf'=>$gomeOrder);
		 $core_http = kernel::single('base_httpclient');
		 $url='http://127.0.0.1/erp/script/fetchGomeOrder.php';
        $msg = $msg.$core_http->set_timeout(10)->post($url,$query_params);
        
			}
			kernel::log("gome:".$msg);
			$msg  = preg_replace("/\s+/", '|', $msg);
			$msg ="导入信息：".trim($msg);
			
		} else {
			$msg = "导入失败！";
		}
		return $msg;
	}
    

	
    function exportTemplate(){
        header("Content-Type: text/csv");
        header("Content-Disposition: attachment; filename=".date('Ymd').".csv");
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        $oObj = &$this->app->model('orders');
        $title1 = $oObj->exportTemplate('order');
        $title2 = $oObj->exportTemplate('obj');
        echo '"'.implode('","',$title1).'"';
        echo "\n\n";
        echo '"'.implode('","',$title2).'"';
    }

    function dispatch(){
        $this->title = '订单调度';
        switch ($_GET['flt'])
        {
			case 'assigned':
                $this->order_type = 'assigned';
                $this->base_filter = array(
                    'assigned'=>'assigned',
                    'abnormal'=>'false',
                    'is_fail'=>'false',
                    'process_status|noequal'=>'cancel',
                    'is_auto'=>'false');
                $this->title = '已分派的订单';
                $finder_aliasname = "order_dispatch_assigned";
                $finder_cols = "order_bn,process_status,ship_name,ship_area,total_amount,op_id,group_id,dispatch_time";
                break;
            case 'notassigned':
                $this->order_type = 'notassigned';
                $this->base_filter = array(
                    'assigned'=>'notassigned',
                    'abnormal'=>'false',
                    'ship_status'=>'0',
                    'is_fail'=>'false',
                    'process_status|noequal'=>'cancel',
                    'is_auto'=>'false');
                $this->title = '未分派的订单';
                $finder_aliasname = "order_dispatch_notassigned";
                $finder_cols = "createtime,shop_id,ship_area,is_cod,total_amount,payment,shipping,mark_type";
                break;
        }
        $this->finder('ome_mdl_orders',array(
           'title' => $this->title,
           'actions' => array(
               array('label'=>'订单分派','submit'=>'index.php?app=ome&ctl=admin_order&act=dispatching','target'=>'dialog::{width:400,height:200,title:\'订单分派\'}'),
//               array('label'=>'订单分派统计','href'=>'index.php?app=ome&ctl=admin_order&act=count_dispatch','target'=>'dialog::{width:1000,height:400,title:\'订单分派统计\'}'),
           ),
           'base_filter' => $this->base_filter,
           'use_buildin_new_dialog' => false,
           'use_buildin_set_tag'=>false,
           'use_buildin_recycle'=>false,
           'use_buildin_export'=>false,
           'use_buildin_import'=>false,
           'use_buildin_filter'=>true,
           'finder_aliasname'=>$finder_aliasname,
           'finder_cols'=>$finder_cols,
        ));
    }

    function confirm(){
        if ($_GET['flt'] == 'unmyown'){
            $this->order_type = 'unmyown';
            $this->title = '订单确认 - 我的待处理订单';
            $this->base_filter['op_id'] = kernel::single('desktop_user')->get_id();
            $this->base_filter['assigned'] = 'assigned';
            $this->base_filter['abnormal'] = "false";
            $this->base_filter['order_confirm_filter'] = "group_id > 0";
            $this->base_filter['is_fail'] = 'false';

            if(!isset($_GET['view'])){
                $this->base_filter['process_status'] = array('unconfirmed','confirmed','splitting');
            }

            // 超级管理员
            if(kernel::single('desktop_user')->is_super()){
                if(isset($this->base_filter['op_id']))
                    unset($this->base_filter['op_id']);

                if(isset($this->base_filter['group_id']))
                    unset($this->base_filter['group_id']);

                $this->base_filter['order_confirm_filter'] = "(group_id>0 OR op_id>0)";
            }

            $this->finder('ome_mdl_orders',array(
               'title'=>$this->title,
               'actions'=>$this->action,
               'base_filter' => $this->base_filter,
               'use_buildin_new_dialog' => false,
               'use_buildin_set_tag'=>false,
               'use_buildin_recycle'=>false,
               'use_buildin_export'=>false,
               'use_buildin_import'=>false,
               'use_buildin_filter'=>true,
               'orderBy' => 'createtime desc',
               'finder_aliasname'=>'order_confirm',
               'finder_cols'=>'_func_0,column_confirm,order_bn,process_status,ship_name,ship_area,total_amount,op_id,group_id,dispatch_time,pay_status,is_cod,ship_status',
            ));
            
        }elseif($_GET['flt'] == 'myown'){
            $this->order_type = 'myown';
            $this->title = '订单确认 - 我的已处理订单';
            $this->base_filter = array('op_id'=>kernel::single('desktop_user')->get_id());
            $this->base_filter['assigned'] = 'assigned';
            $this->base_filter['abnormal'] = "false";
            $this->base_filter['is_fail'] = 'false';
//            $this->base_filter['order_confirm_filter'] = "(is_cod='true' OR pay_status in ('1','4','5'))";

            if(!isset($_GET['view'])){
                $this->base_filter['process_status'] = array('splited','remain_cancel','cancel');
            }

            if(kernel::single('desktop_user')->is_super()){
                if(isset($this->base_filter['op_id']))
                    unset($this->base_filter['op_id']);
            }

            $this->finder('ome_mdl_orders',array(
               'title'=>$this->title,
               'actions'=>$this->action,
               'base_filter' => $this->base_filter,
               'use_buildin_new_dialog' => false,
               'use_buildin_set_tag'=>false,
               'use_buildin_recycle'=>false,
               'use_buildin_export'=>false,
               'use_buildin_import'=>false,
               'use_buildin_filter'=>true,
               'orderBy' => 'createtime desc',
               'finder_aliasname'=>'order_confirm',
               'finder_cols'=>'_func_0,column_confirm,order_bn,process_status,ship_name,ship_area,total_amount,op_id,group_id,dispatch_time',
            ));
        }elseif($_GET['flt'] == 'ourgroup'){
            $this->order_type = 'ourgroup';
            $this->title = '订单确认 - 本组的订单';
            $group_id = "";
            $oGroup = &$this->app->model("groups");
            $op_group = $oGroup->get_group(kernel::single('desktop_user')->get_id());
            if($op_group && is_array($op_group)){
                foreach($op_group as $v){
                    $group_id[] = $v['group_id'];
                }
            }
            $this->base_filter = array('group_id'=>$group_id);
            $this->base_filter['assigned'] = 'assigned';
            $this->base_filter['abnormal'] = "false";
            $this->base_filter['is_fail'] = 'false';
            $this->base_filter['process_status'] = array('unconfirmed','confirmed','splitting','splited','remain_cancel');

            if(kernel::single('desktop_user')->is_super()){
                if(isset($this->base_filter['group_id']))
                    unset($this->base_filter['group_id']);
            }

            $this->finder('ome_mdl_orders',array(
               'title'=>$this->title,
               'actions'=>$this->action,
               'base_filter' => $this->base_filter,
               'use_buildin_new_dialog' => false,
               'use_buildin_set_tag'=>false,
               'use_buildin_recycle'=>false,
               'use_buildin_export'=>false,
               'use_buildin_import'=>false,
               'use_buildin_filter'=>true,
               'orderBy' => 'createtime desc',
               'finder_aliasname'=>'order_confirm',
               'finder_cols'=>'_func_0,column_confirm,order_bn,process_status,ship_name,ship_area,total_amount,op_id,group_id,dispatch_time',
            ));
        }
    }

    public function claim()
    {
        $this->begin('index.php?app=ome&ctl=admin_order&act=confirm&flt=ourgroup');
        $order = $admin = array();

        // 数据验证
        $order['id'] = $_GET['order_id'];
        if (empty($order['id']))
        {
            $this->end(false, app::get('ome')->_('请选择要操作的数据项。'));
            return;
        }
        if (is_array($order['id']))
        {
            foreach ($order['id'] as $value)
            {
                if (!is_numeric($value))
                {
                    $this->end(false, app::get('ome')->_('数据类型不正确。'));
                    return;
                }
            }
        }
        else
        {
            if (!is_numeric($order['id']))
            {
                $this->end(false, app::get('ome')->_('数据类型不正确。'));
                return;
            }
        }

        $admin['account_id'] = $_SESSION['account']['shopadmin'];
        if ($admin['account_id'] <= 0)
        {
            $this->end(false, app::get('ome')->_('账户ID不能为空。'));
            return;
        }

        $mdl_orders = $this->app->model('orders');
        $result = $mdl_orders->db->select(sprintf("SELECT count(*) as _count FROM `%s` WHERE order_id IN ('%s') AND (op_id IS NULL OR op_id = 0 OR op_id = '')", $mdl_orders->table_name(1), implode("','", $order['id'])));
        if (intval($result[0]['_count']) !== 1)
        {
            $this->end(false, app::get('ome')->_('订单已被领取。'));
            return;
        }

        // 数据处理
        if ($mdl_orders->update(array('op_id' => $admin['account_id']), array('order_id' => $order['id'])))
            $this->end(true, app::get('ome')->_('领取操作成功。'));
        else
            $this->end(false, app::get('ome')->_('领取操作失败。'));

        unset($order, $admin);
        return;
    }

    function count_dispatch($data=''){
        if ($_POST){
            $start  = $_POST['start'];
            $end    = $_POST['end'];
            $group_id = $_POST['group'];
            $op_id  = $_POST['operator'];

            $where = '';
            if ($op_id != ''){
                $where .= " AND o.op_id = $op_id ";
            }
            if ($group_id != ''){
                $where .= " AND o.group_id = $group_id ";
            }
            if ($start != '' && $end != ''){
                $s = strtotime($start. ' 00:00:00');
                $e = strtotime($end. ' 23:59:59');
                $where .= " AND (o.dt_begin >= $s AND o.dt_begin <= $e) ";
            }
        }else {
            if ($data){
                if ($data == 'today'){
                    $day_s = strtotime(date('Y-m-d'). ' 00:00:00');
                    $day_e = strtotime(date('Y-m-d'). ' 23:59:59');
                    $where = " AND (o.dt_begin >= $day_s AND o.dt_begin <= $day_e) ";
                }elseif ($data == 'twodays'){
                    $day_s = strtotime('-2 day  00:00:00');
                    $day_e = strtotime(date('Y-m-d'). ' 23:59:59');
                    $where = " AND (o.dt_begin >= $day_s AND o.dt_begin <= $day_e) ";
                }
            }else {
                $where = ' AND 1';
            }
        }
        $oObj = &$this->app->model('orders');

        //all
        $all = $oObj->get_all($where);

        //group
        $group = $oObj->get_group($where);

        //operator
        $operator = $oObj->get_operator($where);
        $groups = $this->app->model('groups')->getList('group_id,name',array('g_type'=>'confirm'),0,-1);
        $ops = $oObj->get_confirm_ops();

        $this->pagedata['groups'] = $groups;
        $this->pagedata['ops'] = $ops;
        $this->pagedata['all'] = $all;
        $this->pagedata['group'] = $group;
        $this->pagedata['operator'] = $operator;
        $this->display('admin/order/count_order.html');
    }

    function dispatching(){
        $oGroup = &$this->app->model('groups');
        $groups = $oGroup->getList('group_id,name',array('g_type'=>'confirm'));
        $this->pagedata['groups'] = $groups;
        $this->display("admin/order/dispatching.html");
    }

    function do_dispatch(){
        $data = array('group_id'=>$_POST['new_group_id'],'op_id'=>$_POST['new_op_id'],'dt_begin'=>time());

        $filter = $_POST;
        unset($filter['_finder']);
        unset($filter['new_group_id']);
        unset($filter['new_op_id']);

        $oOrder = &$this->app->model('orders');

        if(!$_POST['new_op_id']) $data['op_id'] = NULL;
        if(!$_POST['new_group_id']) $data['group_id'] = NULL;
        $data['dispatch_time'] = time();//分派时间

        $post = $_POST['isSelectedAll']=='_ALL_'?array($_POST['isSelectedAll']):$_POST['order_id'];

        $oOrder->dispatch($data,$filter,$post);

        echo "<script>$$('.dialog').getLast().retrieve('instance').close();</script>";
    }

    function do_cancel($order_id)
    {
        $oOrder = &$this->app->model('orders');
        $orderdata = $oOrder->dump($order_id);
        if ($_POST)
        {
            $memo = "订单被取消 ".$_POST['memo'];
            $oOrder->cancel($order_id,$memo);

            echo "<script>window.finderGroup[$(document.body).getElement('input[name^=_finder\[finder_id\]]').value].refresh();$$('.dialog').getLast().retrieve('instance').close();</script>";
        }
        $this->pagedata['order'] = $orderdata;
        $this->display("admin/order/detail_cancel.html");
    }

    function do_confirm($order_id){
        $oOrder = &$this->app->model("orders");
        $order = $oOrder->dump($order_id);
        $this->pagedata['is_splited'] = $order['process_status']=='splitting'?'false':'true';
        $opInfo = kernel::single('ome_func')->getDesktopUser();
        $user_id = $opInfo['op_id'];
        $is_supp = kernel::single('desktop_user')->is_super();

        if ($order['op_id'] != $user_id && $order['op_id'] != '' && !$is_supp){
            header("content-type:text/html; charset=utf-8");
            echo "<script>alert('此订单已分配给其他人');window.close();</script>";
            exit;
        }elseif ($order['is_cod'] == false && $order['pay_status'] == '3'){
            header("content-type:text/html; charset=utf-8");
            echo "<script>alert('请完成付款后，再进行确认');window.close();</script>";
            exit;
        }else {
            if ($order['op_id'] == '' && !$is_supp){
                $oo['order_id'] = $order_id;
                $oo['op_id'] = $user_id;
                $oOrder->save($oo);
            }
        }

        $split_type = $this->app->getConf('ome.order.split_type');

        $oMember = &$this->app->model("members");

        $member = $oMember->dump($order['member_id']);


        $item_list = $oOrder->getItemBranchStore($order_id);
        $order_items = $item_list;
        if($order_items){
            $oDelivery = &$this->app->model("delivery");
            foreach($order_items as $obj_type=>$object_type){
                foreach($object_type as $obj_id=>$obj){
                    foreach($obj['order_items'] as $k=>$item){
                        if ($item['item_type'] == 'pkg' && $item['delete'] == 'true'){
                            unset($item_list[$obj_type][$obj_id]);
                            continue;
                        }
                    }
                }
            }
        }

        $branch_list = $oOrder->getBranchByOrder($order_id);

        /*if($branch_list){
            if($split_type == 'branch'){
                //当拆分的模式是按照仓库来拆时，应该只筛选出所有货品都能发货的仓库
                $avaliable_branch = array();
                $item_branch_list = array();
                $item_branch_list_string = array();
                $i = 0;

                foreach($item_list as $obj_type=>$object_type){
                    foreach($object_type as $obj_id=>$obj){
                        foreach($obj['order_items'] as $k=>$item){
                            $item_branch_list[] = array_keys($item['branch_store']);
                            $item_branch_list_string[] = "\$item_branch_list[$i]";
                            $i ++;
                        }
                    }
                }

                eval("\$avaliable_branch=array_intersect(".implode(",",$item_branch_list_string).");");

                if($avaliable_branch){
                    $t_branch_list = $branch_list;
                    foreach($branch_list as $k=>$v){
                        if(!in_array($v['branch_id'],$avaliable_branch)){
                            unset($t_branch_list[$k]);
                        }
                    }
                    $branch_list = $t_branch_list;
                    unset($t_branch_list);
                }else{
                    $branch_list = array();
                }
            }

            /*$corp_list = array();
            $oBranch = &$this->app->model("branch");
            foreach($branch_list as $v){
                $corp_list[$v['branch_id']] = $oBranch->get_corp($v['branch_id']);
            }
            $this->pagedata['corp_list'] = $corp_list;*/
        //}

        $object_alias = $oOrder->getOrderObjectAlias($order_id);

        if(!preg_match("/^mainland:/", $order['consignee']['area'])){
            $region='';
            $newregion='';
            foreach(explode("/",$order['consignee']['area']) as $k=>$v){
                $region.=$v.' ';
            }
        }else{
            $newregion = $order['consignee']['area'];
        }

        //获取当前订单的上下条订单
        //---获取finder选择条件
        $ini_filter = $_GET['filter'];
        $finder_filter = unserialize(urldecode($ini_filter));
        unset($finder_filter['process_status']);unset($finder_filter['pay_status']);
        unset($finder_filter['group_id']);unset($finder_filter['is_cod']);

        $filter = '';
        if ($finder_filter){
            $colOrder = $oOrder->getColumns();
            foreach ($finder_filter as $key=>$v){
                if (!$key || !in_array($key,$colOrder)) continue;
                $filter .= " AND `".$key."`='".$v."' ";
            }
        }
        $filter .= " AND `process_status` IN ('unconfirmed','splitting','confirmed') ";
        $filter .= " AND `group_id`>'0' AND (is_cod='true' OR pay_status NOT IN('0','2')) ";
        $up_order = $oOrder->getOrderUpNext($order_id, $filter, '<');
        $next_order = $oOrder->getOrderUpNext($order_id, $filter, '>');
        $this->pagedata['up_order'] = $up_order;
        $this->pagedata['next_order'] = $next_order;
        $this->pagedata['filter'] = urlencode($ini_filter);

        $order['mark_text'] = unserialize($order['mark_text']);
        $order['custom_mark'] = unserialize($order['custom_mark']);

        //单仓库
        if($this->app->getConf('ome.branch.mode') == 'single' && count($branch_list)>1){
            $branch_list = array($branch_list[0]);
        }

        //下单时间离当前的时间差
        $difftime = kernel::single('ome_func')->toTimeDiff(time(),$order['createtime']);
        $order['difftime'] = $difftime['d'].'天'.$difftime['h'].'小时'.$difftime['m'].'分';

        //发货单
        $oDelivery = &$this->app->model("delivery");
        $order_delivery_list = $oDelivery->getDeliversByOrderId($order_id);
        //$order_delivery_item_list = $oDelivery->getDeliverItemByOrderId($order_id);
         /*$new_list = array();
        foreach($order_delivery_list as $k=>$delivery){
            foreach($branch_list as $branch_item){
                if($delivery['branch_id'] == $branch_item['branch_id']){
                    $tmp_branch_name = $branch_item['name'];
                    break;
                }
            }
            $order_delivery_list[$k]['branch_name'] = $tmp_branch_name; //取仓库名字
            $order_delivery_list[$k] = $oDelivery->dump($delivery['delivery_id'],'*','delivery_items');
            //$order_delivery_list[$k]['delivery_items'] = $order_delivery_item_list[$delivery['delivery_id']];
        }  */

        $this->pagedata['order_delivery_list'] = $order_delivery_list;

        //选中有库存的仓库，默认不选中
        $selected_branch_id = 0;

        foreach($branch_list as $branch){
            $selected_branch = false;
            foreach($item_list as $obj_type=>$objs){
                foreach($objs as $obj){
                    foreach($obj['order_items'] as $item){
                        if($item['delete']=='false'){
                            if($item['branch_store'][$branch['branch_id']] >= $item['left_nums'] && $item['left_nums'] !=0){
                                $selected_branch = true;
                            }else{
                                if ($selected_branch) continue;
                                $selected_branch = false;
                            }
                        }
                    }
                }
            }

            if($selected_branch){
                $tmp_branch_id[$branch['branch_id']] = $branch['weight'];
            }
        }
        if ($tmp_branch_id) arsort($tmp_branch_id);
        list($main,$add,$region_id) = explode(':',$order['consignee']['area']);
        $region_ = app::get('ectools')->model('regions')->dump($region_id);
        if ($region_){
            $ls = explode(',', $region_['region_path']);
            $ls = array_filter($ls);
            sort($ls);
        }
        if ($tmp_branch_id)
        foreach ($tmp_branch_id as $b_id => $weight){
            $b_a_list = $this->app->model('branch_area')->getList('region_id',array('branch_id'=>$b_id),0,-1);
            if ($b_a_list){
                foreach ($b_a_list as $b){
                    $tb[] = $b['region_id'];
                }
                foreach ($ls as $l){
                    if (in_array($l, $tb)){
                        $selected_branch_id = $b_id;
                        break;
                    }
                }
                if ($selected_branch_id) break;
            }else {
                $selected_branch_id = $b_id;
                break;
            }
        }
        if ($selected_branch_id==0) $selected_branch_id = $tmp_branch_id[0];
        $this->pagedata['selected_branch_id'] = $selected_branch_id;

        //订单代销人会员信息
        $oSellagent = &app::get('ome')->model('order_selling_agent');
        $sellagent_detail = $oSellagent->dump(array('order_id'=>$order_id));
        if (!empty($sellagent_detail)){
            $this->pagedata['sellagent'] = $sellagent_detail;
        }
        //发货人信息
        $order_consigner = false;
        if ($order['consigner']){
            foreach ($order['consigner'] as $shipper){
                if (!empty($shipper)){
                    $order_consigner = true;
                    break;
                }
            }
        }
        if ($order_consigner == false){
            //读取店铺发货人信息
            $oShop = &app::get('ome')->model('shop');
            $shop_detail = $oShop->dump(array('shop_id'=>$order['shop_id']));
            $order['consigner'] = array(
                'name' => $shop_detail['default_sender'],
                'mobile' => $shop_detail['mobile'],
                'tel' => $shop_detail['tel'],
                'zip' => $shop_detail['zip'],
                'email' => $shop_detail['email'],
                'area' => $shop_detail['area'],
                'addr' => $shop_detail['addr'],
            );
        }
        $configlist = array();
        if ($servicelist = kernel::servicelist('ome.service.order.confirm'))
        foreach ($servicelist as $object => $instance){
            if (method_exists($instance, 'view_list')){
                $list = $instance->view_list();
                $configlist = array_merge($configlist, is_array($list) ? $list : array());
            }
        }

        $this->pagedata['configlist'] = $configlist;
        $this->pagedata['region'] = $region;
        $this->pagedata['newregion'] = $newregion;
        $this->pagedata['order_id'] = $order_id;
        ome_order_func::order_sdf_extend($item_list);
        $this->pagedata['item_list'] = $item_list;
        $this->pagedata['branch_list'] = $branch_list;
        $this->pagedata['object_alias'] = $object_alias;
        //$this->pagedata['obj_type_arr'] = kernel::single('ome_order_func')->get_obj_type();
        $this->pagedata['member'] = $member;
		$order['createtime'] = date('Y-m-d',$order['createtime']);
        $this->pagedata['order'] = $order;
        $this->pagedata['split_type'] = $split_type;
        $this->pagedata['branch_mode'] = $this->app->getConf('ome.branch.mode');
        $this->pagedata['base_dir'] = kernel::base_url();
        $this->pagedata['url'] = kernel::base_url()."/app/".$this->app->app_id;
        //finder_id
        if (isset($_GET['find_id'])){
            $finder_id = $_GET['find_id'];
        }else{
            $finder_id = $_GET['finder_id'];
        }
        $this->pagedata['finder_id'] = $finder_id;
        $this->singlepage("admin/order/confirm.html");
    }

    function finish_confirm(){
        $oOrder = &$this->app->model("orders");
        $this->begin("index.php?app=ome&ctl=admin_order&act=do_confirm&p[0]=".$_POST['order_id']);
        $region = $_POST['consignee'];
        list($package,$region_name,$region_id) = explode(':',$region['area']);
        if (!$region_id){
            $is_area = false;
            //非本地标准地区转换
            $area = $region['area'];
            kernel::single('ome_func')->region_validate($area);
            $is_correct_area = kernel::single('ome_func')->is_correct_region($area);
            if ($is_correct_area == true){
                 $is_area = true;
                 //更新地区字段
                 $order_update = array(
                   'order_id' => $_POST['order_id'],
                   'consignee' => array(
                       'area' => $area
                   ),
                 );
                 $oOrder->save($order_update);
            }
        }else{
            $is_area = true;
        }

        $action = explode("-",$_POST['do_action']);
        if(in_array(1,$action)){
            $order = $oOrder->dump($_POST['order_id'],'pause');
            if ($order['pause'] == 'true'){
                $this->end(false, '请先恢复订单' );
            }
            //订单确认
            if ($is_area == false){
                $this->end(false,'收货地区与系统不匹配，请编辑订单进行修改！');
            }
            $ret = $oOrder->confirm($_POST['order_id']);
            if(!$ret){
                $this->end(false,'该订单已不需要确认');
                return false;
            }
        }
        //生成发货单
        if(in_array(2,$action)){
            $order = $oOrder->dump($_POST['order_id'],'pause');
            if ($order['pause'] == 'true'){
                $this->end(false, '请先恢复订单' );
            }
            if ($order['process_status'] == 'cancel'){
                $this->end(false, '订单已取消，无法生成发货单' );
            }
            if ($is_area == false){
                $this->end(false,'收货地区与系统不匹配，请编辑订单进行修改！');
            }

            $_postdelivery = json_decode(urldecode($_POST['order_items']),true);
            $products = $_postdelivery['products'];
            $branch_id = $_postdelivery['branch_id'];
            $deliverys = array();
            $dlys = array();
            if ($products){
                foreach ($products as $pk=>$pv){
                    $item_id = $pv['itemid'];
                    $pv['item_id'] = $pv['itemid'];
                    $pv['order_id'] = $_POST['order_id'];
                    $dlys[$branch_id]['delivery_items'][$item_id] = $pv;
                    unset($pv['order_id'],$pv['itemid'],$pv['item_id']);
                    $deliverys[$branch_id]['delivery_items'][$item_id] = $pv;
                }
            }
            $deliverys[$branch_id]['branch_id'] = $branch_id;
            $deliverys[$branch_id]['logi_id'] = $_postdelivery['logi_id'];
            $_POST['delivery'] = $deliverys;
            unset($_postdelivery, $products, $deliverys, $_POST['order_items']);

            $pro_id = array();
            if($_POST['delivery']){
                $new_delivery = $_POST['delivery'];
                foreach($_POST['delivery'] as $branch_id=>$delivery){
                    if (empty($delivery['logi_id'])){
                        $this->end(false, '请选择物流公司');
                    }
                    $new_delivery_items = array();
                    if ($delivery['delivery_items']){
                        foreach($delivery['delivery_items'] as $item){
                            if ($new_delivery_items[$item['product_id']]){
                                $item['number'] += $new_delivery_items[$item['product_id']]['number'];
                                $new_delivery_items[$item['product_id']] = $item;
                            }else{
                                $new_delivery_items[$item['product_id']] = $item;
                            }
                        }

                        if(count($new_delivery_items) == 0){
                            unset($new_delivery[$branch_id]);
                        }else{
                            $new_delivery[$branch_id]['order_items'] = $dlys[$branch_id]['delivery_items'];
                            $new_delivery[$branch_id]['delivery_items'] = $new_delivery_items;
                            $new_delivery[$branch_id]['consignee'] = $_POST['consignee'];
                        }
                        $pro_id[$item['product_id']] += $new_delivery_items[$item['product_id']]['number'];
                    }
                }
            }
            $product = array();
            $name = array();
            $item_list = $oOrder->getItemBranchStore($_POST['order_id']);
            if ($item_list)
            foreach ($item_list as $il){
                if ($il)
                foreach ($il as $var){
                    if ($var)
                    foreach ($var['order_items'] as $v){
                        $name[$v['product_id']] = $v['name'];
                        $product[$v['product_id']] += $v['left_nums'];
                    }
                }
            }
            if ($product){
                foreach ($product as $id => $number){
                    if ($number < $pro_id[$id]){
                        $this->end(false, $name[$id].'：此商品已拆分完');
                        return ;
                    }
                }
            }
            //订单拆分，产生发货单
            $oOrder->mkDelivery($_POST['order_id'],$new_delivery);
            $item_list = $oOrder->getItemBranchStore($_POST['order_id']);
            if ($item_list)
            foreach ($item_list as $il){
                if ($il)
                foreach ($il as $var){
                    if ($var)
                    foreach ($var['order_items'] as $v){
                        if ($v['left_nums'] >0){
                            $this->end(true, '订单拆分成功');
                        }
                    }
                }
            }
            $this->end(true, '订单拆分完成');
        }
        if(in_array(4,$action)){
            //订单暂停
            if ($oOrder->pauseOrder($_POST['order_id'])){
                $this->end(true, '订单暂停成功' );
            }else {
                $this->end(true, '订单暂停失败' );
            }
        }
        if(in_array(5,$action)){
            //订单恢复
            if ($oOrder->renewOrder($_POST['order_id'])){
                $this->end(true, '订单恢复成功');
            }else {
                $this->end(true, '订单恢复失败' );
            }
        }
        $this->end(true, '订单处理成功');
    }

    function abnormal(){
        $this->order_type = 'abnormal';
        $this->finder('ome_mdl_orders',array(
           'title'=>'异常订单',
           'base_filter'=>array('abnormal'=>'true','is_fail'=>'false'),
           'use_buildin_new_dialog' => false,
           'use_buildin_set_tag'=>false,
           'use_buildin_recycle'=>false,
           'use_buildin_export'=>false,
           'use_buildin_import'=>false,
           'use_buildin_filter'=>true,
           'use_view_tab'=>true,
           'object_method'=>array('count'=>'countAbnormal','getlist'=>'getlistAbnormal')
        ));
    }

    function do_abnormal($order_id){
        $oAbnormal = &$this->app->model('abnormal');
        $oOrder = &$this->app->model('orders');
        $ordersdetail = $oOrder->dump(array('order_id'=>$order_id),"op_id,group_id");

        //组织分派所需的参数
        $this->pagedata['op_id'] = $ordersdetail['op_id'];
        $this->pagedata['group_id'] = $ordersdetail['group_id'];
        $this->pagedata['dt_begin'] = strtotime(date('Y-m-d',time()));
        $this->pagedata['dispatch_time'] = strtotime(date('Y-m-d',time()));

        if($_POST){
            $this->begin("index.php?app=ome&ctl=admin_order&act=confirm&flt=".$_POST['flt']);
            $abnormal_data = $_POST['abnormal'];

            $oOrder->set_abnormal($abnormal_data);
            $oOrder->cancel_delivery($order_id);//取消发货单
            $this->end(true, '成功');
            //echo "<script>$$('.dialog').getLast().retrieve('instance').close();</script>";
            return true;
        }

        $abnormal = $oAbnormal->getList("*",array("order_id"=>$order_id));

        $oAbnormal_type = &$this->app->model('abnormal_type');

        $abnormal_type = $oAbnormal_type->getList("*");

        $abnormal[0]['abnormal_memo'] = unserialize($abnormal[0]['abnormal_memo']);
        $this->pagedata['abnormal'] = $abnormal[0];
        $this->pagedata['abnormal_type'] = $abnormal_type;
        $this->pagedata['order_id'] = $order_id;
        $this->pagedata['set_abnormal'] = true;
        $this->pagedata['flt'] = $_GET['flt'];

        $this->display("admin/order/detail_abnormal.html");
    }

    //状态冲突
    function conflict(){
        $this->finder('ome_mdl_orders',array(
           'title'=>'状态冲突',
           'base_filter'=>array('pay_status'=>'5','ship_status'=>'1','is_fail'=>'false'),
           'use_buildin_new_dialog' => false,
           'use_buildin_set_tag'=>false,
           'use_buildin_recycle'=>false,
           'use_buildin_export'=>false,
           'use_buildin_import'=>false,
           'use_buildin_filter'=>true,
        ));
    }

    function do_export()
    {
        $selected = $_POST['order_id'];
        $oOrder = &$this->app->model('orders');
        $isSelected = $_POST['isSelectedAll'];
        //如果是选择了全部
        if ($isSelected == '_ALL_')
        {

            $order_ids = $oOrder->getOrderId();
            print_r($order_ids);
        }
        else
        {
            if ($selected)
            foreach ($selected as $order_id)
            {
                $temp_data = $oOrder->order_detail($order_id);
                $order_info = array();
                $order_info['order_id'] = $temp_data['order_id'];

                $export_data[] = $order_info;
            }
            echo '<pre>';
            print_r($export_data);
            echo '</pre>';
        }
    }

    function get_printable_orders($param)
    {
        $validator  = $this->app->model('validate');
        if (!$validator->valid())
        {
            return "validate failed";
        }
        if (!$param['time_from'] && !$param['time_to'])
        {
            return array();
        }
        $payed = isset($param['payed'])?$param['payed']:1;
        $to_print = isset($param['to_print'])?$param['to_print']:1;
        $time_from = isset($param['time_from'])?$param['time_from']:0;
        $time_to = isset($param['time_to'])?$param['time_to']:time();
        $page = isset($param['page'])?$param['page']:1;
        $limit = isset($param['limit'])?$param['limit']:1;

        $oOrder = $this->app->model('orders');
        $sql = 'SELECT `order_id` from sdb_ome_orders WHERE 1';
        if ($payed)
        {
            $sql .= ' and `pay_status`=1';
        }
        if ($to_print)
        {
            $sql .= ' and `print_finish` = \'true\'';
        }
        if ($time_from)
        {
            $sql .= " and `createtime`> '$time_from'";
        }
        if ($time_to)
        {
            $sql .= " and `createtime`< '$time_to'";
        }
        $sql .= " limit ".($page-1)*$limit.','.$limit;
        $order_ids = kernel::database()->db->select($sql);
        $return = array();
        foreach ($order_ids as $orderinfo)
        {
            $return[] = $oOrder->dump($orderinfo['order_id']);
        }
        //记录日志
        return $return;
    }


     /*
    * 查看售后服务对应日志记录
    */
    function show_aftersale_log($return_id){
        $opObj = $this->app->model('operation_log');
        $log = $opObj->read_log(array('obj_id'=>$return_id,'obj_type'=>'return_product@ome'));

        $this->pagedata['log'] = $log;
        $this->display("admin/order/aftersale_log.html");
    }

    /*
     * 追加备注 append_memo
     */
    function append_memo(){

        $Orders = &$this->app->model('orders');
        $orders['order_id'] = $_POST['order']['order_id'];
        if ($_POST['oldmemo']){
            $oldmemo = $_POST['oldmemo'].'<br/>';
        }
        $memo  = $oldmemo.$_POST['order']['mark_text'].'  &nbsp;&nbsp;('.date('Y-m-d H:i:s',time()).' by '.kernel::single('desktop_user')->get_name().')';
        $orders['mark_text'] = $memo;
        $Orders->save($orders);
        echo $memo;
    }

    function view_edit($order_id){
        $oOrder = &$this->app->model('orders');
        $order = $oOrder->dump($order_id);
        if ($order['pause'] == 'false'){
            exit('请先暂停订单');
        }
        if ($order['process_status'] == 'cancel'){
            exit('订单已取消，无法再编辑订单');
        }

        $item_list = $oOrder->getItemBranchStore($order_id);

        if(!preg_match("/^mainland:/", $order['consignee']['area'])){
            $region='';
            $newregion='';
            foreach(explode("/",$order['consignee']['area']) as $k=>$v){
                $region.=$v.' ';
            }
        }else{
            $newregion = $order['consignee']['area'];
        }

        $this->pagedata['region'] = $region;
        $this->pagedata['newregion'] = $newregion;
        $this->pagedata['order_id'] = $order_id;
        $order['custom_mark'] = unserialize($order['custom_mark']);
        if ($order['custom_mark'])
        foreach ($order['custom_mark'] as $k=>$v){
            if (!strstr($v['op_time'], "-")){
                $v['op_time'] = date('Y-m-d H:i:s',$v['op_time']);
                $order['custom_mark'][$k]['op_time'] = $v['op_time'];
            }
        }
        $order['mark_text'] = unserialize($order['mark_text']);
        if ($order['mark_text'])
        foreach ($order['mark_text'] as $k=>$v){
            if (!strstr($v['op_time'], "-")){
                $v['op_time'] = date('Y-m-d H:i:s',$v['op_time']);
                $order['mark_text'][$k]['op_time'] = $v['op_time'];
            }
        }

        if(app::get('omepkg')->is_installed()){
            $flag = true;
        }else{
            $flag = false;
        }

        //订单代销人会员信息
        $oSellagent = &app::get('ome')->model('order_selling_agent');
        $sellagent_detail = $oSellagent->dump(array('order_id'=>$order_id));
        if (!empty($sellagent_detail)){
            $this->pagedata['sellagent'] = $sellagent_detail;
        }
        //发货人信息
        $order_consigner = false;
        if ($order['consigner']){
            foreach ($order['consigner'] as $shipper){
                if (!empty($shipper)){
                    $order_consigner = true;
                    break;
                }
            }
        }
        $oShop = &app::get('ome')->model('shop');
        $shop_detail = $oShop->dump(array('shop_id'=>$order['shop_id']));
        $b2b_shop_list = ome_shop_type::b2b_shop_list();
        if (in_array($shop_detail['node_type'], $b2b_shop_list)){
            $this->pagedata['b2b'] = true;
        }

        //购买人信息
        $memberObj = &app::get('ome')->model('members');
        $members_detail = $memberObj->dump($order['member_id']);

        $this->pagedata['order'] = $order;
        $this->pagedata['member'] = $members_detail;
        ome_order_func::order_sdf_extend($item_list);
        $obj_config = array();
        if ($servicelist = kernel::servicelist('ome.service.order.edit'))
        foreach ($servicelist as $obj =>$instance){
            if (method_exists($instance,'config_list')){
                $tmp_conf = $instance->config_list();
                $obj_config = array_merge($obj_config,empty($tmp_conf)?array():$tmp_conf);
            }
        }
        foreach ($item_list as $obj => $idata){
            if (isset($obj_config[$obj])){
                $obj_config[$obj]['load'] = true;
                $obj_config[$obj]['objs'] = $idata;
            }else {
                $obj_config[$obj] = $obj_config['goods'];
                $obj_config[$obj]['load']   = true;
                $obj_config[$obj]['is_add'] = false;
                $obj_config[$obj]['objs']   = $idata;
            }
        }
        if ($flag==false) {
            if (isset($obj_config['pkg'])){
                $obj_config['pkg']['is_add'] = false;
            }
        }
        $conf_list = array();
        if ($obj_config)
        foreach ($obj_config as $name => $conf){
            if ($conf['load']==true) {
                $conf_list[$name] = $conf;
                continue;
            }else if($conf['is_add']==true){
                $conf_list[$name] = $conf;
                $conf_list[$name]['load'] = true;
            }
        }
        ksort($conf_list);
        $this->pagedata['conf_list'] = $conf_list;
        $this->pagedata['item_list_log'] = base64_encode(serialize($item_list));
        $this->pagedata['item_list'] = $item_list;

        $this->singlepage("admin/order/order_edit.html");
    }


     /*
     * 余单撤消
     */
    function remain_order_cancel(){

        if ($_POST['remain_order_cancel'] == 'do'){

            $order_id = intval($_POST['order_id']);
            $this->begin("index.php?app=ome&ctl=admin_order&act=do_confirm&p[0]=".$order_id);

            $reback_price = $_POST['refund_money'];//退款金额
            $revock_price = $_POST['revock_price'];//撤销商品总额
            $result = kernel::single('ome_order_order')->order_revoke($order_id,$reback_price,$revock_price);
            if ($result != true){
                $result = false;
                $msg = '失败';
            }else{
                $result = true;
                $msg = '成功';
            }
            $this->end($result, app::get('base')->_("余单撤消".$msg));

        }
    }

    /*
     * 显示余单撤消确认页面
     * @param string $order_id 订单号
     * @return 确认页面
     */
    function remain_order_cancel_confirm(){

       $order_id = intval($_GET['order_id']);
       $oOrder = &$this->app->model("orders");
       $oRefund = &$this->app->model("refunds");
       $order = $oOrder->dump($order_id, 'process_status,order_bn,payed,order_id,total_amount,cost_item,cost_freight,cost_protect,cost_tax,cost_payment,pmt_goods,pmt_order,discount');
       $diff_price = kernel::single('ome_order_func')->order_items_diff_money($order_id);
       if ($order['process_status'] == 'remain_cancel') die('余单撤销状态的订单,无法再次撤销！');
       //if (!$diff_price) die('未发货商品总额为0,无法再次撤销！');
       $order['diff_price'] = $diff_price;
       if ($order['payed'] > $diff_price){
           $refund_money = $diff_price;
       }else{
           $refund_money = $order['payed'];
       }
       //已退款金额
       $refunds = $oRefund->getList('money', array('order_id'=>$order_id), 0, -1);
       $refunded = '0';
       if ($refunds){
           foreach ($refunds as $refund_val){
               $refunded += $refund_val['money'];
           }
       }
       $order['refunded'] = $refunded;
       //商品明细
       $item_list = $oOrder->getItemBranchStore($order_id);
       ome_order_func::order_sdf_extend($item_list);
       $this->pagedata['item_list'] = $item_list;

       $order['refund_money'] = $refund_money;
       $this->pagedata['order'] = $order;
       $this->singlepage('admin/order/remain_order_cancel.html');
    }

    /*
     * 余单撤消退款
     * @param string $order_id 订单号
     * @param string $refund_money 退款金额
     * @return 退款窗口
     */
    function remain_order_cancel_refund($order_id='',$refund_money='0'){

        $objOrder = &$this->app->model('orders');
        if ($_POST){
            $this->begin('');
            $orderdata = $objOrder->order_detail($_POST['order_id']);
            if($_POST['refund_money'] > $orderdata['payed'] ){
                $this->end(false,'退款金额不能大于剩余金额');
            }else{
                $return = kernel::single('ome_refund_apply')->refund_apply_add($_POST);
                if ($return['result'] == true){
                    $result  = true;
                }else{
                    $result = false;
                }
                $msg = $return['msg'];
                $this->end($result, app::get('base')->_($msg));
            }
        }else{
            $order = $objOrder->order_detail($order_id);
            $addon['from'] = 'remain_order_cancel';
            $result = kernel::single('ome_refund_apply')->show_refund_html($order_id, '', $refund_money, $addon);
            if ($result['result'] == true){
                return $result;
            }else{
                exit($result['msg']);
            }
        }
    }

    function finish_edit(){
        $oOrder = &$this->app->model("orders");
        $oShop  = &$this->app->model('shop');

        $order_id       = $_POST['order_id'];
        $order          = $oOrder->dump($order_id);
        $shop_detail    = $oShop->dump(array('shop_id'=>$order['shop_id']), 'node_type');
        $node_type      = $shop_detail['node_type'];

        //B2B检测是否允许编辑该订单
        $b2b_shop = ome_shop_type::b2b_shop_list();
        if (in_array($node_type, $b2b_shop)){
            $allow_edit = true;
            if ($allow_edit_service = kernel::service('ome.order.edit')){
                $error = '';
                if(method_exists($allow_edit_service, 'is_allow_edit')){
                    $order_edit_info = array();
                    $order_edit_info['bn'] = $_POST['bn_list'];
                    $order_edit_info['shop_id'] = $_POST['shop_id'];
                    $allow_edit = $allow_edit_service->is_allow_edit($order_edit_info, $error);
                }
            }
            if (!$allow_edit){
                $this->begin('');
                if (empty($error)) $error = '保存失败';
                $this->end(false, $error);
            }
        }

        if ($_POST['do_action'] != 0){
        	//echo 'ew';
        	//return ;
            //操作
            $this->begin('');
            //$this->begin("index.php?app=ome&ctl=admin_order&act=view_edit&p[0]=".$_POST['order_id']);

            $pObj           = &$this->app->model("products");
            $oSpec          = &$this->app->model('specification');
            $oOrderItm      = &$this->app->model("order_items");
            $oOrderObj      = &$this->app->model("order_objects");
            $oSpecvalue     = &$this->app->model('spec_values');
            $oOperation_log = &$this->app->model('operation_log');

            $post = $_POST;
            if ($post['do_action'] != 2){
                if ($order['pause'] == 'false'){
                    $this->end(false, "请先暂停订单");
                }
            }
            $is_address_change  = false;//地址是否变更
            $is_order_change    = false;//是否需要修改
            $is_goods_modify    = false;//是否编辑过商品
            $is_consigner_change = false;

            //收货人信息
            $consignee = array_diff_assoc($post['order']['consignee'],$order['consignee']);
            //发货人信息
            $consigner = array_diff_assoc((array)$post['order']['consigner'],(array)$order['consigner']);
            if (!empty($consigner)){
                $is_consigner_change = true;
            }
            if (!empty($consignee)){
                $is_address_change = true;
            }
            $goods      = $post['goods'];
            $pkg        = $post['pkg'];
            $gift       = $post['gift'];
            $giftpkg    = $post['giftpkg'];

            $objtype = $post['objtype'];

            if (empty($goods) && empty($pkg) && empty($gift) && empty($giftpkg)){
                $this->end(false, "订单不能没有商品");
            }
//var_dump($post);
            $new_order = $post['order'];
            $total = 0;
            if ($objtype && is_array($objtype)){
                $rs = kernel::single("ome_order_edit")->process_order_objtype($objtype,$post);
            }else {
                $this->end(false, "订单不能没有商品");
            }
            $obj    = $rs['obj'];
            $new    = $rs['new'];
            $total  = $rs['total'];

            $is_order_change = $rs['is_order_change'];
            $is_goods_modify = $rs['is_goods_modify'];;//是否编辑过商品

            //修改订单折扣金额
            if (strval($order['discount']) != strval($post['discount'])){
                $is_order_change = true;
            }

            if ($is_order_change == true || $is_address_change == true || $is_consigner_change == true){
                //打回已存在的发货单
                $oOrder->rebackDeliveryByOrderId($order_id);

                $objMath    = kernel::single('ectools_math');
                $pro_total  = $order['cost_item'];
                $diff       = $objMath->number_minus(array($total, $pro_total));
                $discount   = strval($post['discount']);
                $order_type = $post['order_type'];

                $new_order['order_id']      = $order_id;
                $new_order['cost_item']     = $total;
                $new_order['total_amount']  = $objMath->number_plus(array($total,$order['shipping']['cost_shipping'],$order['shipping']['cost_protect'],$order['cost_tax'],$order['payinfo']['cost_payment']));
                $new_order['total_amount']  = $objMath->number_minus(array($new_order['total_amount'],$order['pmt_goods'],$order['pmt_order']));
                $new_order['total_amount']  = $objMath->number_plus(array($new_order['total_amount'],$discount));
                $new_order['discount']      = $discount;
                $new_order['cur_amount']	= $new_order['total_amount'];
                $new_order['order_type']	= $order_type;

                if ($new_order['total_amount'] < 0){
                    $this->end(false, "订单折扣金额输入有误");
                }
                if ($consignee) $new_order['consignee'] = $consignee;
                if ($consigner) $new_order['consigner'] = $consigner;

                if ($is_goods_modify == true){
                    $new_order['is_modify'] = 'true';
                }
                $new_order['old_amount']     = $order['total_amount'];
                $new_order['confirm']        = 'N';
                $new_order['process_status'] = 'unconfirmed';
                $new_order['pause']          = 'false';

                $oOperation_log->write_log('order_edit@ome',$_POST['order_id'],"订单修改并恢复");
                //将未修改以前的数据存储以便查询
                if($is_address_change ==true || $is_goods_modify == true || $is_order_change == true){
                    $log_id = $oOperation_log->getList('log_id',array('operation'=>'order_edit@ome','obj_id'=>$_POST['order_id']),0,1,'log_id DESC');
                    $log_id = $log_id[0]['log_id'];
                    $_POST['item_list'] = unserialize(base64_decode($_POST['item_list']));
                    $this->app->model('orders')->write_log_detail($log_id,$_POST);
                }

                //更新order
                $oOrder->save($new_order);
               // return;
                //调用公共方法更改订单支付状态
                kernel::single('ome_order_func')->update_order_pay_status($order_id);
                if ($is_order_change == true){
                    //更新order_objects,order_items
                    foreach ($obj as $k => $o){
                        $tmp = array();
                        $tmp = $o['items'];
                        unset($o['items']);

                        $oOrderObj->save($o);
                        foreach ($tmp as $oo){
                            $oOrderItm->save($oo);
                        }
                    }
                    if ($new)
                    foreach ($new as $ao){
                        //新增新的object
                        $tmp = array();
                        $tmp = $ao['items'];
                        unset($ao['items']);

                        $oOrderObj->save($ao);
                        foreach ($tmp as $aoo){
                            //新增新的item
                            $aoo['obj_id'] = $ao['obj_id'];

                            $product_id = $aoo['product_id'];
                            $product_info = $pObj->dump(array('product_id'=>$product_id),"spec_desc");
                            $spec_desc = $product_info['spec_desc'];
                            if ($spec_desc['spec_value_id'])
                            foreach ($spec_desc['spec_value_id'] as $sk=>$sv){
                                 $tmp = array();
                                 $specval = $oSpecvalue->dump($sv,"spec_value,spec_id");
                                 $tmp['value'] = $specval['spec_value'];
                                 $spec = $oSpec->dump($specval['spec_id'],"spec_name");
                                 $tmp['label'] = $spec['spec_name'];
                                 $productattr[] = $tmp;
                            }

                            if ($productattr) $product_attr['product_attr'] = $productattr;
                            if ($product_attr) $aoo['addon'] = serialize($product_attr); //货品属性//

                            $oOrderItm->save($aoo);
                        }
                    }
                }
               //修改交易收货人信息 API
                if ($is_address_change == true){
                    if ($service_order = kernel::servicelist('service.order')){
                        foreach($service_order as $object=>$instance){
                           if(method_exists($instance, 'update_shippinginfo')){
                              $instance->update_shippinginfo($order_id);
                           }
                        }
                    }
                }
                //订单编辑API
                if ($is_order_change == true){
                    if ($service_order = kernel::servicelist('service.order')){
                        foreach($service_order as $object=>$instance){
                           if(method_exists($instance, 'update_order')){
                              $instance->update_order($order_id);
                           }
                        }
                    }
                }
                //订单恢复状态同步
                if ($service_order = kernel::servicelist('service.order')){
                    foreach($service_order as $object=>$instance){
                        if(method_exists($instance, 'update_order_pause_status')){
                           $instance->update_order_pause_status($order_id, 'false');
                        }
                    }
                }
                $this->end(true, "修改成功");
            }else{
                //恢复order
                $oOrder->renewOrder($order_id);
            }
            $this->end(true, "完成");
        }else {
            //判断，校验
            $this->begin('');

            $oOrder     = &$this->app->model("orders");
            $oOrderItm  = &$this->app->model("order_items");
            $oOrderObj  = &$this->app->model("order_objects");
            $pObj       = &$this->app->model("products");
            $goodsObj   = &$this->app->model("goods");
            $order_id   = $_POST['order_id'];
            $order      = $oOrder->dump($order_id);

            if ($order['pause'] == 'false'){
                $this->end(false, '请先暂停订单');
            }
            $post       = $_POST;
            $consignee  = array_diff_assoc($post['order']['consignee'],$order['consignee']);
            $goods      = $post['goods'];
            $pkg        = $post['pkg'];
            $gift       = $post['gift'];
            $giftpkg    = $post['giftpkg'];
            $objtype    = $post['objtype'];
            if (empty($goods) && empty($pkg) && empty($gift) && empty($giftpkg)){
                $this->end(false, "订单不能没有商品");
            }

            if ($objtype && is_array($objtype)){
                //是否有数据提交
                $rs = kernel::single("ome_order_edit")->is_null($objtype,$post);
                if ($rs == true) $this->end(false, "订单不能没有商品");
                //校验数据正确性
                $rs = kernel::single("ome_order_edit")->valid_order_objtype($objtype,$post);
                if ($rs != true && $rs['flag'] == false){
                    $this->end(false, $rs['msg']);
                }
            }else {
                $this->end(false, "订单不能没有商品");
            }
            $this->end(true, '验证完成');
        }
    }

    function getProducts(){
        $pro_id = $_POST['product_id'];

        if (is_array($pro_id)){
            $filter['product_id'] = $pro_id;
        }

        if($_GET['bn']){

           $filter = array(
               'bn|head'=>$_GET['bn']
           );
        }

        if($_GET['name']){
            $filter = array(
               'name|head'=>$_GET['name']
           );
        }

        $pObj = &$this->app->model('products');
        $data = $pObj->getList('product_id,bn,name,price,wholesale,barcode,spec_info,store',$filter,0,-1);
        $list = array();
        if ($data)
        foreach ($data as $v){
            $v['type'] = 'goods';
            $list[] = $v;
        }

        echo "window.autocompleter_json=".json_encode($list);
    }

    function findProduct(){
        if ($_GET['branch_id']){
            $filter['branch_id'] = $_GET['branch_id'];
            $params = array(
                            'base_filter' => $filter,
                            'title'=>'商品列表',
                            'use_buildin_new_dialog' => false,
                            'use_buildin_set_tag'=>false,
                            'use_buildin_recycle'=>false,
                            'use_buildin_export'=>false,
                            'use_buildin_import'=>false,
                            'use_buildin_filter'=>true,
                            'use_view_tab' => false,
                            'object_method'=>array('count'=>'countAnother','getlist'=>'getListAnother')
                        );
            $this->finder('ome_mdl_products', $params);
        }else {
            $params = array(
                            'title'=>'商品列表',
                            'use_buildin_new_dialog' => false,
                            'use_buildin_set_tag'=>false,
                            'use_buildin_recycle'=>false,
                            'use_buildin_export'=>false,
                            'use_buildin_import'=>false,
                            'use_view_tab' => false,
                            'use_buildin_filter'=>true,
                        );
            $this->finder('ome_mdl_products', $params);
        }
    }

    function do_check($order_id, $newtotal, $total){

        $orefapply = &$this->app->model('orders');
        $order = $orefapply->order_detail($order_id);
        $is_cod = $_GET['is_cod'];
        $pay_status = intval($_GET['pay_status']);
        $newtotal = strval($newtotal);
        $total = strval($total);
        $payed = $order['payed'];

        $is_change = $payed != $newtotal ? 1 : 0;
        if ($payed > $newtotal){
            $refund_money = $payed - $newtotal;

            if ($order['pause'] == 'false'){
                exit("请先暂停订单");
            }
            $addon['from'] = 'order_edit';
            $result = kernel::single('ome_refund_apply')->show_refund_html($order_id, '', $refund_money, $addon);
            if ($result['result'] == true){
                return $result;
            }else{
                exit($result['msg']);
            }
        }else{

            $this->pagedata['is_cod'] = $is_cod;
            $this->pagedata['is_change'] = $is_change;
            $this->pagedata['change_value'] = round(abs($newtotal-$payed),3);
            $this->pagedata['newtotal'] = $newtotal;
            $this->pagedata['total'] = $total;
            $this->pagedata['payed'] = $payed;
            $this->display("admin/order/order_edit_check.html");
        }
    }

    function do_refund(){

        $objOrder = &app::get('ome')->model('orders');
        $this->begin("index.php?app=ome&ctl=admin_order&act=do_refund&p[0]=".$_POST['order_id']);
        if($_POST){
            $orderdata = $objOrder->order_detail($_POST['order_id']);
            if ($orderdata['pause'] == 'false'){
                $this->end(false, '请先暂停订单');
            }
            $return = kernel::single('ome_refund_apply')->refund_apply_add($_POST);
            if ($return['result'] == true){
                $result  = true;
            }else{
                $result = false;
            }
            $msg = $return['msg'];

            $this->end($result, app::get('base')->_($msg));
        }
    }

    function addOrder(){
        if ($_POST){
            $this->begin("index.php?app=ome&ctl=admin_order&act=addOrder");
            if (!$_POST['type']){
                $this->end(false,'请选择订单类型');
            }
            $brObj = &$this->app->model('branch');
            $branch_list = $brObj->getBranchByUser();
            /*if (count($branch_list) == 0){
                $this->end(false, '管理员未关联仓库，请先关联仓库');
            }elseif (count($branch_list) > 1){
                $this->end(false, '管理员已关联多个仓库，无法操作');
            }*/
            $type = $_POST['type'];
            if ($type == 'normal'){
                $this->addNormalOrder();
            }else {
                $this->addSaleOrder();
            }
        }else
            $this->page("admin/order/order_choice.html");
    }

    function addNormalOrder(){
        $shopObj = &$this->app->model("shop");
        $shopData = $shopObj->getList('shop_id,name,shop_type');
        $this->pagedata['shopData'] = $shopData;
        $this->pagedata['creatime'] = date("Y-m-d",time());
        $this->page("admin/order/add_normal_order.html");
    }

    function doAddNormalOrder(){
        $this->begin("index.php?app=ome&ctl=admin_order&act=addNormalOrder");

        $pObj = &$this->app->model("products");
        $oObj = &$this->app->model("orders");

        $post = $_POST;

        $post['consignee']['r_time']    = '任意日期 任意时间段';
        $post['consignee']['area']      = $post['address_id'];

        $post['member_id'] = $post['id'];
        if (!$post['member_id']) $this->end(false, '请选择会员');
        if (!$post['cost_shipping']) $post['cost_shipping'] = 0;
        if (!$post['discount']) $post['discount'] = 0;

        $consignee = $post['consignee'];
        if ($consignee){
            if (!$consignee['name']){
                $this->end(false, '请填写收件人');
            }
            if (!$consignee['area']){
                $this->end(false, '请填写配送三级区域');
            }
            if (!$consignee['addr']){
                $this->end(false, '请填写配送地址');
            }
            if (!$consignee['mobile'] && !$consignee['telephone']){
                $this->end(false, '收件人手机和固定电话必须填写一项');
            }
        }else {
            $this->end(false, '请填写配送地址信息');
        }
        $ship = $_POST['address_id'];

        $shipping = array();
        if ($ship){
            $shipping = array(
                'shipping_name' => '快递',
                'cost_shipping' => $post['cost_shipping'],
                'is_protect' => 'false',
                'cost_protect' => 0,
                'is_cod' => 'false'
            );

        }else {
            $this->end(false, '请选择物流信息');
        }
        $num = $_POST['num'];
        $price = $_POST['price'];
        if (!$num) $this->end(false, '请选择商品');
        $tmp_num = $num;
        $pkg_num = array();
        foreach ($num as $key => $v){
            $no = explode('_',$key);
            if ($no[0] == 'pkg') {
                unset($tmp_num[$key]);
                $pkg_num[$key] = array(
                    'id' => $no[1],
                    'num' => $v
                );
            }
            if ($v < 1 || $v > 499999){
                $this->end(false, '数量必须大于1且小于499999');
            }
        }
        if (!$price) $this->end(false, '请选择商品');
        foreach ($price as $v){
            if ($v < 0){
                $this->end(false, '请填写正确的价格');
            }
        }

        $num = $tmp_num;
        $iorder = $post['order'];

        $iorder['consignee'] = $consignee;
        $iorder['shipping'] = $shipping;

        //goods
        if ($num)
        foreach ($num as $k => $i){
            $p = $pObj->dump($k);
            $iorder['order_objects'][] = array(
                'obj_type' => 'goods',
                'obj_alias' => 'goods',
                'goods_id' => $p['goods_id'],
                'bn' => $p['bn'],
                'name' => $p['name'],
                'price' => $price[$k],
                'amount' => $price[$k],
                'quantity' => $i,
                'order_items' => array(
                    array(
                        'product_id' => $p['product_id'],
                        'bn' => $p['bn'],
                        'name' => $p['name'],
                        'price' => $price[$k],
                        'amount' => $price[$k],
                        'nums' => $i,
                        'quantity' => $i,
                        'sendnum' => 0,
                        'item_type' => 'product'
                    )
                )
            );
            $weight += $i*$p['weight'];
            $item_cost += $i*$price[$k];
        }
        //pkg
        if ( $pkg_num ) {
            $pkgPobj = &app::get('omepkg')->model('pkg_product');
            $pkgGobj = &app::get('omepkg')->model('pkg_goods');
            foreach ($pkg_num as $key =>$val){
                $pkgprolist = $pkgPobj->getList('*', array('goods_id'=>$val['id']), 0, -1);
                $order_items = array();
                foreach ($pkgprolist as $v){
                    $p = $pObj->dump($v['product_id']);
                    $order_items[] = array(
                        'product_id' => $p['product_id'],
                        'bn' => $p['bn'],
                        'name' => $p['name'],
                        'price' => 0,
                        'amount' => 0,
                        'nums' => $v['pkgnum'] * $val['num'],
                        'quantity' => $v['pkgnum'] * $val['num'],
                        'sendnum' => 0,
                        'item_type' => 'pkg'
                    );
                }
                $pkgg = $pkgGobj->dump( $val['id'] );
                $iorder['order_objects'][] = array(
                    'obj_type' => 'pkg',
                    'obj_alias' => $pkgg['name'],
                    'goods_id' => $p['goods_id'],
                    'bn' => $pkgg['pkg_bn'],
                    'name' => $pkgg['name'],
                    'price' => $price[$key],
                    'amount' => $price[$key] * $val['num'],
                    'quantity' => $val['num'],
                    'order_items' => $order_items
                );
                $weight += $val['num'] * $pkgg['weight'];
                $item_cost += $val['num'] * $price[$key];
            }
        }
        if ($post['customer_memo']){
            $c_memo =  htmlspecialchars($post['customer_memo']);
            $c_memo = array('op_name'=>kernel::single('desktop_user')->get_name(), 'op_time'=>date('Y-m-d H:i',time()), 'op_content'=>$c_memo);
            $tmp[]  = $c_memo;
            $iorder['custom_mark']  = serialize($tmp);
            $tmp = null;
        }
        if ($post['order_memo']){
            $o_memo =  htmlspecialchars($post['order_memo']);
            $o_memo = array('op_name'=>kernel::single('desktop_user')->get_name(), 'op_time'=>date('Y-m-d H:i',time()), 'op_content'=>$o_memo);
            $tmp[]  = $o_memo;
            $iorder['mark_text']    = serialize($tmp);
            $tmp = null;
        }

        if($post['shop_id']){
            $shop = explode('*',$post['shop_id']);
            $iorder['shop_id'] = $shop[0];
            $iorder['shop_type'] = $shop[1];
        }

        $iorder['member_id']    = $post['member_id'];
        $iorder['weight']       = $weight;
        $iorder['title']        = $p['bn'].$p['name'];
        $iorder['itemnum']      = count($iorder['order_objects']);
        $iorder['createtime']   = time();
        $iorder['ip']           = $_SERVER['REMOTE_ADDR'];
        $iorder['cost_item']    = $item_cost;
        $iorder['currency']     = 'CNY';
        $iorder['pmt_order']    = $post['pmt_order'];
        $iorder['discount']     = $post['discount'];
        $iorder['total_amount'] = $item_cost+$post['cost_shipping']-$post['pmt_order']+$post['discount'];
        $iorder['is_delivery']  = 'Y';
        $iorder['source']  = 'local';//订单来源标识，local为本地新建订单

        if ($iorder['total_amount'] < 0) $this->end(false,'订单金额不能小于0');

        $iorder['order_bn'] = $oObj->gen_id();

        //设置订单失败时间
        $iorder['order_limit_time'] = time() + 60*(app::get('ome')->getConf('ome.order.failtime'));

        $oObj->create_order($iorder);
        $this->end(true, '创建成功');
    }

    /*function addSaleOrder(){
        $this->begin("index.php?app=ome&ctl=admin_order&act=addSaleOrder");
        $brObj = &$this->app->model('branch');
        //$mbObj = &$this->app->model('members');
        $branch_list = $brObj->getBranchByUser();

        if (count($branch_list) == 0){
            $this->end(false, '管理员未关联仓库，请先关联仓库');
        }elseif (count($branch_list) > 1){
            $this->end(false, '管理员已关联多个仓库，无法操作');
        }

        //$members = $mbObj->getList('member_id,uname','',0,-1);

        //$this->pagedata['member'] = $members;
        $this->pagedata['branch'] = array_shift($branch_list);
        $this->page("admin/order/add_sale_order.html");
    }*/

    function doAddSaleOrder(){
        $this->begin("index.php?app=ome&ctl=admin_order&act=addSaleOrder");

        $pObj = &$this->app->model("products");
        $bpObj = &$this->app->model("branch_product");
        $oObj = &$this->app->model("orders");
        $dObj = &$this->app->model("delivery");

        $post = $_POST;

        $logi_id = $post['logi_id'];
        $logi_no = $post['logi_no'];

        $post['consignee']['r_time']    = '任意日期 任意时间段';
        $post['member_id']          = $post['id'];
        $post['consignee']['area']  = $post['address_id'];

        if (!$post['member_id']) $this->end(false, '请选择会员');
        if (!$post['address_id']) $this->end(false, '请选择收货地址');
        if (!$logi_id) $this->end(false, '请选择物流公司');
        if (!$post['cost_shipping']) $post['cost_shipping'] = 0;
        if (!$post['discount']) $post['discount'] = 0;

        if ($dObj->existExpressNo($logi_no)) $this->end(false, '快递单号重复');

        $consignee = $post['consignee'];
        if ($consignee){
            if (!$consignee['name']){
                $this->end(false, '请填写收件人');
            }
            if (!$consignee['area']){
                $this->end(false, '请填写配送三级区域');
            }
            if (!$consignee['addr']){
                $this->end(false, '请填写配送地址');
            }
            if (!$consignee['zip']){
                $this->end(false, '请填写配送邮政编码');
            }
            /*if (!$consignee['telephone']){
                $this->end(false, '请填写收件人电话');
            }*/
            if (!$consignee['mobile']){
                $this->end(false, '请填写收件人手机');
            }
        }else {
            $this->end(false, '请填写配送地址信息');
        }
        $ship = $post['address_id'];
        $corpObj = &$this->app->model('dly_corp');
        $corp = $corpObj->dump($logi_id, 'corp_id,name');

        $shipping = array();
        if ($ship){
            $shipping = array(
                'shipping_name' => $corp['name'],
                'cost_shipping' => $post['cost_shipping'],
                'is_protect' => 'false',
                'cost_protect' => 0,
                'is_cod' => 'true'
            );

        }else {
            $this->end(false, '请选择物流信息');
        }
        $num = $post['num'];
        $price = $post['price'];
        if (!$num) $this->end(false, '请选择商品');
        $tmp_num = $num;
        $pkg_num = array();
        $pro = array();
        foreach ($num as $ky => $v){
            if ($v < 1 || $v > 499999){
                $this->end(false, '数量必须大于1且小于499999');
            }
            $no = explode('_',$ky);
            if ($no[0] == 'pkg'){
                unset($tmp_num[$ky]);
                $pkg_num[$ky] = array(
                    'id' => $no[1],
                    'num' => $v
                );
                $pkgplist = app::get('omepkg')->model('pkg_product')->getList('*',array('goods_id'=>$no[1]),0,-1);
                foreach ($pkgplist as $val){
                    $pro[$val['product_id']] = isset($pro[$val['product_id']])?$pro[$val['product_id']]+$v*$val['pkgnum']:$v*$val['pkgnum'];
                    $bp = $bpObj->dump(array('product_id'=>$val['product_id'],'branch_id'=>$post['branch_id']),'store');
                    if ($pro[$val['product_id']] > $bp['store']) {
                        $this->end(false, '捆绑商品库存数量不足');
                    }
                }
                continue;
            }
            $pp = $pObj->dump($ky,'name');
            $bp = $bpObj->dump(array('product_id'=>$ky,'branch_id'=>$post['branch_id']),'store');
            $pro[$ky] = isset($pro[$ky])?$pro[$ky]+$v:$v;
            if ($pro[$ky] > $bp['store']){
                $this->end(false, $pp['name'].':库存数量不足');
            }
        }
        if (!$price) $this->end(false, '请选择商品');
        foreach ($price as $v){
            if ($v < 0){
                $this->end(false, '请填写正确的价格');
            }
        }
        $num = $tmp_num;
        $iorder = array();

        $iorder['consignee'] = $consignee;
        $iorder['shipping'] = $shipping;
        $delivery = array();
        $dly_item = array();
        //goods
        foreach ($num as $k => $i){
            $p = $pObj->dump($k);
            $iorder['order_objects'][] = array(
                'obj_type' => 'goods',
                'obj_alias' => 'goods',
                'goods_id' => $p['goods_id'],
                'bn' => $p['bn'],
                'name' => $p['name'],
                'price' => $price[$k],
                'amount' => $price[$k],
                'quantity' => $i,
                'order_items' => array(
                    array(
                        'product_id' => $p['product_id'],
                        'bn' => $p['bn'],
                        'name' => $p['name'],
                        'price' => $price[$k],
                        'amount' => $price[$k],
                        'nums' => $i,
                        'quantity' => $i,
                        'sendnum' => 0,
                        'item_type' => 'product'
                    )
                )

            );

            $dly_item[$p['product_id']] = array(
                'product_id' => $p['product_id'],
                'item_type' => 'product',
                'bn' => $p['bn'],
                'product_name' => $p['name'],
                'number' => $i
            );
            $weight += $i*$p['weight'];
            $item_cost += $i*$price[$k];
        }

        //pkg
        if ( $pkg_num ) {
            $pkgPobj = &app::get('omepkg')->model('pkg_product');
            $pkgGobj = &app::get('omepkg')->model('pkg_goods');
            foreach ($pkg_num as $key =>$val){
                $pkgprolist = $pkgPobj->getList('*', array('goods_id'=>$val['id']), 0, -1);
                foreach ($pkgprolist as $v){
                    $p = $pObj->dump($v['product_id']);
                    $order_items[] = array(
                        'product_id' => $p['product_id'],
                        'bn' => $p['bn'],
                        'name' => $p['name'],
                        'price' => 0,
                        'amount' => 0,
                        'nums' => $v['pkgnum'] * $val['num'],
                        'quantity' => $v['pkgnum'] * $val['num'],
                        'sendnum' => 0,
                        'item_type' => 'pkg'
                    );
                    if (isset($dly_item[$p['product_id']])) {
                        $dly_item[$p['product_id']]['number'] += $v['pkgnum'] * $val['num'];
                    }else {
                        $dly_item[$p['product_id']] = array(
                            'product_id' => $p['product_id'],
                            'bn' => $p['bn'],
                            'product_name' => $p['name'],
                            'number' => $v['pkgnum'] * $val['num']
                        );
                    }
                }
                $pkgg = $pkgGobj->dump( $val['id'] );
                $iorder['order_objects'][] = array(
                    'obj_type' => 'pkg',
                    'obj_alias' => $pkgg['name'],
                    'goods_id' => $p['goods_id'],
                    'bn' => $pkgg['pkg_bn'],
                    'name' => $pkgg['name'],
                    'price' => $price[$key],
                    'amount' => $price[$key] * $val['num'],
                    'quantity' => $val['num'],
                    'order_items' => $order_items
                );
                $weight += $val['num'] * $pkgg['weight'];
                $item_cost += $val['num'] * $price[$key];
            }
        }
        if ($post['customer_memo']){
            $c_memo =  htmlspecialchars($post['customer_memo']);
            $c_memo = array('op_name'=>kernel::single('desktop_user')->get_name(), 'op_time'=>date('Y-m-d H:i',time()), 'op_content'=>$c_memo);
            $tmp[]  = $c_memo;
            $iorder['custom_mark']  = serialize($tmp);
            $tmp = null;
        }
        if ($post['order_memo']){
            $o_memo =  htmlspecialchars($post['order_memo']);
            $o_memo = array('op_name'=>kernel::single('desktop_user')->get_name(), 'op_time'=>date('Y-m-d H:i',time()), 'op_content'=>$o_memo);
            $tmp[]  = $o_memo;
            $iorder['mark_text']    = serialize($tmp);
            $tmp = null;
        }

        $iorder['member_id']    = $post['member_id'];
        $iorder['weight']       = $weight;
        $iorder['title']        = $p['bn'].$p['name'];
        $iorder['itemnum']      = count($iorder['order_objects']);
        $iorder['createtime']   = time();
        $iorder['ip']           = $_SERVER['REMOTE_ADDR'];
        $iorder['cost_item']    = $item_cost;
        $iorder['currency']     = 'CNY';
        $iorder['pmt_order']    = $post['pmt_order'];
        $iorder['discount']     = $post['discount'];
        $iorder['total_amount'] = $item_cost+$_POST['cost_shipping']-$post['pmt_order']+$post['discount'];
        $iorder['is_delivery']  = 'Y';
        $iorder['order_type']   = 'sale';

        if ($iorder['total_amount'] < 0) $this->end(false,'订单金额不能小于0');

        $iorder['order_bn'] = $oObj->gen_id();

        $oObj->create_order($iorder);
        $order_id = $iorder['order_id'];
        //确认
        $oObj->confirm($order_id);

        if ($dly_item)
        foreach ($dly_item as $item){
            $delivery['delivery_items'][] = $item;
        }

        $delivery['member_id']  = $iorder['member_id'];
        $delivery['is_cod']     = $iorder['is_cod'];
        $delivery['new_weight'] = $weight;
        $delivery['logi_id']    = $corp['corp_id'];
        $delivery['logi_name']  = $corp['name'];
        $delivery['branch_id']  = $post['branch_id'];
        $delivery['delivery_cost_actual'] = $post['cost_shiiping'];

        //生成发货单
        $ids = $oObj->mkDelivery($order_id, array($delivery));
        $dObj = $this->app->model("delivery");
        //处理发货单
        if (!$ids) $this->end(false, '订单生成失败');
        foreach ($ids as $id){
            //打印完
            $dly = array(
                    'delivery_id' => $id,
                    'stock_status' => true,
                    'expre_status' => true,
                    'deliv_status' => true,
                    'logi_no' => $logi_no
            );
            $dObj->save($dly);
            //校验完成
            $re = $dObj->verifyDelivery(array('delivery_id'=>$id,'is_bind'=>'false'));
            if (!$re) $this->end(false, '创建失败');
            //发货
            $dObj->consignDelivery($id,$weight);
        }

        $this->end(true, '创建成功');
    }

    function getMemberAddress($mem_id=0){
        if (!$mem_id){
            $mem_id = $_POST['member_id'];
        }
        $oObj = $this->app->model("orders");
        $list = $oObj->getList('order_id',array('member_id'=>$mem_id),0,-1);
        if ($list){
            $address = array();
            foreach ($list as $v){
                $order = $oObj->dump($v['order_id']);
                $string = $order['consignee'];
                $md5 = md5(serialize($string));
                $tmp = explode(':',$string['area']);
                $string['id'] = $tmp[2];
                $address[$md5] = $string;
            }
            sort($address);
            echo json_encode($address);
        }
    }

    function getMembers(){
        $mbObj = &$this->app->model('members');

        if($_POST['mobile']){
            $data = $mbObj->get_member($_POST['mobile'],'mobile');
        }elseif ($_POST['uname']){
            $data = $mbObj->get_member($_POST['uname'],'uname');
        }elseif ($_POST['member_id']){
            $filter = array(
               'member_id'=>$_POST['member_id']
            );
            $data = $mbObj->getList('member_id,uname,area,mobile,email,sex',$filter,0,-1);
        }

        if ($data)
        foreach ($data as $k => $v){
            $data[$k]['sex'] = $v['sex']=='male' ? '男' : '女';
        }

        if ($data){
            echo "window.autocompleter_json=".json_encode($data);
            exit;
        }
        echo "";
    }

    function getCorpArea(){
        $region = $_POST['region'];
        $dcaObj = &$this->app->model('dly_corp_area');
        $dcObj = &$this->app->model('dly_corp');
        if ($region){
            $tmp = explode(':',$region);
            $region_id = $tmp[2];
            $data = $dcaObj->getCorpByRegionId($region_id);
            if (!$data) $data = $dcObj->getList('corp_id,name','',0,-1);
            echo json_encode($data);
        }else {
            $data = $dcObj->getList('corp_id,name','',0,-1);
            echo json_encode($data);
        }
    }

    function addNewAddress(){
        if (isset($_GET['area'])){
            $this->pagedata['region'] = $_GET['area'];
        }
        $this->display("admin/order/add_new_address.html");
    }

    function getConsingee(){
        $string = $_POST['consignee'];
        if ($string['area']){
            $region = explode(':', $string['area']);
            if (!$region[2]){
                return false;
            }
        }else {
            return false;
        }
        $string['id'] = $region[2];
        echo json_encode($string);
    }

   function getCorps(){
        $branch_id = $_POST['branch_id'];
        $oBranch = &$this->app->model("branch");
        $corpList = $oBranch->get_corp($branch_id);
        echo json_encode($corpList);
    }

   function do_confirm_delivery_info_edit($order_id){
       if($order_id){
           $oOrder = &$this->app->model("orders");
           $order = $oOrder->dump($order_id);
           $this->pagedata['order'] = $order;
           $this->display('admin/order/confirm/delivery_info_edit.html');
       }
   }

   function do_confirm_delivery_info($order_id){
       if($order_id){
           $oOrder = &$this->app->model("orders");
           $order = $oOrder->dump($order_id);
           $order['mark_text'] = unserialize($order['mark_text']);
           $order['custom_mark'] = unserialize($order['custom_mark']);
           $this->pagedata['order'] = $order;
           $this->display('admin/order/confirm/delivery_info.html');
       }
   }

   function cancelOrder(){

   }

   function show_operation(){
          $log_id  = $_GET['log_id'];
          $order_id = $_GET['order_id'];
          $ooObj = $this->app->model('orders');
          $operation_history = $ooObj->read_log_detail($order_id,$log_id);
          $this->pagedata['operation_history'] = $operation_history;
          $this->pagedata['operation_detail'] = unserialize($operation_history['order_detail']);
          $region_detail = unserialize($operation_history['order_detail']);
       if(!preg_match("/^mainland:/", $region_detail['log_area'])){
            $region='';
            $newregion='';
            foreach(explode("/",$region_detail['log_area']) as $k=>$v){
                $region.=$v.' ';
            }
        }else{
            $newregion = $region_detail['log_area'];
        }
        $this->pagedata['region'] = $region;
        $this->pagedata['newregion'] = $newregion;
        $this->singlepage('admin/order/operations_order.html');

   }

}
?>